serviceworker.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. class app.ServiceWorker
  2. $.extend @prototype, Events
  3. @isEnabled: ->
  4. !!navigator.serviceWorker and app.config.service_worker_enabled
  5. constructor: ->
  6. @registration = null
  7. @notifyUpdate = true
  8. navigator.serviceWorker.register(app.config.service_worker_path, {scope: '/'})
  9. .then(
  10. (registration) => @updateRegistration(registration),
  11. (error) -> console.error('Could not register service worker:', error)
  12. )
  13. update: ->
  14. return unless @registration
  15. @notifyUpdate = true
  16. return @registration.update().catch(->)
  17. updateInBackground: ->
  18. return unless @registration
  19. @notifyUpdate = false
  20. return @registration.update().catch(->)
  21. reload: ->
  22. return @updateInBackground().then(() -> app.reboot())
  23. updateRegistration: (registration) ->
  24. @registration = registration
  25. $.on @registration, 'updatefound', @onUpdateFound
  26. return
  27. onUpdateFound: =>
  28. $.off @installingRegistration, 'statechange', @onStateChange() if @installingRegistration
  29. @installingRegistration = @registration.installing
  30. $.on @installingRegistration, 'statechange', @onStateChange
  31. return
  32. onStateChange: =>
  33. if @installingRegistration and @installingRegistration.state == 'installed' and navigator.serviceWorker.controller
  34. @installingRegistration = null
  35. @onUpdateReady()
  36. return
  37. onUpdateReady: ->
  38. @trigger 'updateready' if @notifyUpdate
  39. return