serviceworker.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. app.ServiceWorker = class ServiceWorker extends Events {
  2. static isEnabled() {
  3. return !!navigator.serviceWorker && app.config.service_worker_enabled;
  4. }
  5. constructor() {
  6. super();
  7. this.onStateChange = this.onStateChange.bind(this);
  8. this.registration = null;
  9. this.notifyUpdate = true;
  10. navigator.serviceWorker
  11. .register(app.config.service_worker_path, { scope: "/" })
  12. .then(
  13. (registration) => this.updateRegistration(registration),
  14. (error) => console.error("Could not register service worker:", error),
  15. );
  16. }
  17. update() {
  18. if (!this.registration) {
  19. return;
  20. }
  21. this.notifyUpdate = true;
  22. return this.registration.update().catch(() => {});
  23. }
  24. updateInBackground() {
  25. if (!this.registration) {
  26. return;
  27. }
  28. this.notifyUpdate = false;
  29. return this.registration.update().catch(() => {});
  30. }
  31. reload() {
  32. return this.updateInBackground().then(() => app.reboot());
  33. }
  34. updateRegistration(registration) {
  35. this.registration = registration;
  36. $.on(this.registration, "updatefound", () => this.onUpdateFound());
  37. }
  38. onUpdateFound() {
  39. if (this.installingRegistration) {
  40. $.off(this.installingRegistration, "statechange", this.onStateChange);
  41. }
  42. this.installingRegistration = this.registration.installing;
  43. $.on(this.installingRegistration, "statechange", this.onStateChange);
  44. }
  45. onStateChange() {
  46. if (
  47. this.installingRegistration &&
  48. this.installingRegistration.state === "installed" &&
  49. navigator.serviceWorker.controller
  50. ) {
  51. this.installingRegistration = null;
  52. this.onUpdateReady();
  53. }
  54. }
  55. onUpdateReady() {
  56. if (this.notifyUpdate) {
  57. this.trigger("updateready");
  58. }
  59. }
  60. };