1 | import { apiRunner } from "./api-runner-browser"
|
2 |
|
3 | if (
|
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 |
|
17 |
|
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 |
|
25 |
|
26 |
|
27 |
|
28 | window.___swUpdated = true
|
29 |
|
30 | apiRunner(`onServiceWorkerUpdateReady`, { serviceWorker: reg })
|
31 |
|
32 |
|
33 | if (window.___failedResources) {
|
34 | console.log(`resources failed, SW updated - reloading`)
|
35 | window.location.reload()
|
36 | }
|
37 | } else {
|
38 |
|
39 |
|
40 | console.log(`Content is now available offline!`)
|
41 |
|
42 |
|
43 |
|
44 |
|
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 | }
|