UNPKG

2.76 kBJavaScriptView Raw
1import { apiRunner } from "./api-runner-browser"
2
3if (
4 window.location.protocol !== `https:` &&
5 window.location.hostname !== `localhost`
6) {
7 console.error(
8 `Service workers can only be used over HTTPS, or on localhost for development`
9 )
10} else if (`serviceWorker` in navigator) {
11 navigator.serviceWorker
12 .register(`${__BASE_PATH__}/sw.js`)
13 .then(function(reg) {
14 reg.addEventListener(`updatefound`, () => {
15 apiRunner(`onServiceWorkerUpdateFound`, { serviceWorker: reg })
16 // The updatefound event implies that reg.installing is set; see
17 // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
18 const installingWorker = reg.installing
19 console.log(`installingWorker`, installingWorker)
20 installingWorker.addEventListener(`statechange`, () => {
21 switch (installingWorker.state) {
22 case `installed`:
23 if (navigator.serviceWorker.controller) {
24 // At this point, the old content will have been purged and the fresh content will
25 // have been added to the cache.
26
27 // We set a flag so Gatsby Link knows to refresh the page on next navigation attempt
28 window.___swUpdated = true
29 // We call the onServiceWorkerUpdateReady API so users can show update prompts.
30 apiRunner(`onServiceWorkerUpdateReady`, { serviceWorker: reg })
31
32 // If resources failed for the current page, reload.
33 if (window.___failedResources) {
34 console.log(`resources failed, SW updated - reloading`)
35 window.location.reload()
36 }
37 } else {
38 // At this point, everything has been precached.
39 // It's the perfect time to display a "Content is cached for offline use." message.
40 console.log(`Content is now available offline!`)
41
42 // Post to service worker that install is complete.
43 // Delay to allow time for the event listener to be added --
44 // otherwise fetch is called too soon and resources aren't cached.
45 apiRunner(`onServiceWorkerInstalled`, { serviceWorker: reg })
46 }
47 break
48
49 case `redundant`:
50 console.error(`The installing service worker became redundant.`)
51 apiRunner(`onServiceWorkerRedundant`, { serviceWorker: reg })
52 break
53
54 case `activated`:
55 apiRunner(`onServiceWorkerActive`, { serviceWorker: reg })
56 break
57 }
58 })
59 })
60 })
61 .catch(function(e) {
62 console.error(`Error during service worker registration:`, e)
63 })
64}