serviceworker.js 1.7 KB

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