serviceworker.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. 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
  22. .register(app.config.service_worker_path, { scope: "/" })
  23. .then(
  24. (registration) => this.updateRegistration(registration),
  25. (error) => console.error("Could not register service worker:", error),
  26. );
  27. }
  28. update() {
  29. if (!this.registration) {
  30. return;
  31. }
  32. this.notifyUpdate = true;
  33. return this.registration.update().catch(function () {});
  34. }
  35. updateInBackground() {
  36. if (!this.registration) {
  37. return;
  38. }
  39. this.notifyUpdate = false;
  40. return this.registration.update().catch(function () {});
  41. }
  42. reload() {
  43. return this.updateInBackground().then(() => app.reboot());
  44. }
  45. updateRegistration(registration) {
  46. this.registration = registration;
  47. $.on(this.registration, "updatefound", this.onUpdateFound);
  48. }
  49. onUpdateFound() {
  50. if (this.installingRegistration) {
  51. $.off(this.installingRegistration, "statechange", this.onStateChange());
  52. }
  53. this.installingRegistration = this.registration.installing;
  54. $.on(this.installingRegistration, "statechange", this.onStateChange);
  55. }
  56. onStateChange() {
  57. if (
  58. this.installingRegistration &&
  59. this.installingRegistration.state === "installed" &&
  60. navigator.serviceWorker.controller
  61. ) {
  62. this.installingRegistration = null;
  63. this.onUpdateReady();
  64. }
  65. }
  66. onUpdateReady() {
  67. if (this.notifyUpdate) {
  68. this.trigger("updateready");
  69. }
  70. }
  71. };
  72. app.ServiceWorker.initClass();