serviceworker.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Sanity-check the conversion and remove this comment.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS102: Remove unnecessary code created because of implicit returns
  6. * DS206: Consider reworking classes to avoid initClass
  7. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
  8. */
  9. const Cls = (app.ServiceWorker = class ServiceWorker {
  10. static initClass() {
  11. $.extend(this.prototype, Events);
  12. }
  13. static isEnabled() {
  14. return !!navigator.serviceWorker && app.config.service_worker_enabled;
  15. }
  16. constructor() {
  17. this.onUpdateFound = this.onUpdateFound.bind(this);
  18. this.onStateChange = this.onStateChange.bind(this);
  19. this.registration = null;
  20. this.notifyUpdate = true;
  21. navigator.serviceWorker.register(app.config.service_worker_path, {scope: '/'})
  22. .then(
  23. registration => this.updateRegistration(registration),
  24. error => console.error('Could not register service worker:', error));
  25. }
  26. update() {
  27. if (!this.registration) { return; }
  28. this.notifyUpdate = true;
  29. return this.registration.update().catch(function() {});
  30. }
  31. updateInBackground() {
  32. if (!this.registration) { return; }
  33. this.notifyUpdate = false;
  34. return this.registration.update().catch(function() {});
  35. }
  36. reload() {
  37. return this.updateInBackground().then(() => app.reboot());
  38. }
  39. updateRegistration(registration) {
  40. this.registration = registration;
  41. $.on(this.registration, 'updatefound', this.onUpdateFound);
  42. }
  43. onUpdateFound() {
  44. if (this.installingRegistration) { $.off(this.installingRegistration, 'statechange', this.onStateChange()); }
  45. this.installingRegistration = this.registration.installing;
  46. $.on(this.installingRegistration, 'statechange', this.onStateChange);
  47. }
  48. onStateChange() {
  49. if (this.installingRegistration && (this.installingRegistration.state === 'installed') && navigator.serviceWorker.controller) {
  50. this.installingRegistration = null;
  51. this.onUpdateReady();
  52. }
  53. }
  54. onUpdateReady() {
  55. if (this.notifyUpdate) { this.trigger('updateready'); }
  56. }
  57. });
  58. Cls.initClass();