|
1
|
|
|
// https://developers.google.com/web/tools/workbox/modules/workbox-window |
|
2
|
|
|
// All major browsers that support service worker also support native JavaScript |
|
3
|
|
|
// modules, so it's perfectly fine to serve this code to any browsers |
|
4
|
|
|
// (older browsers will just ignore it) |
|
5
|
|
|
// |
|
6
|
|
|
import { Workbox } from 'https://storage.googleapis.com/workbox-cdn/releases/5.0.0-beta.1/workbox-window.prod.mjs'; |
|
7
|
|
|
|
|
8
|
|
|
var supportsServiceWorker = 'serviceWorker' in navigator; |
|
|
|
|
|
|
9
|
|
|
var isNotLocalDevelopment = |
|
10
|
|
|
['localhost', '127'].indexOf(location.hostname) === -1; |
|
11
|
|
|
|
|
12
|
|
|
if (supportsServiceWorker && isNotLocalDevelopment) { |
|
13
|
|
|
const swFileLocation = (window.PUBLIC_URL || '/') + 'sw.js'; |
|
14
|
|
|
const wb = new Workbox(swFileLocation); |
|
15
|
|
|
|
|
16
|
|
|
// Add an event listener to detect when the registered |
|
17
|
|
|
// service worker has installed but is waiting to activate. |
|
18
|
|
|
wb.addEventListener('waiting', event => { |
|
19
|
|
|
// customize the UI prompt accordingly. |
|
20
|
|
|
const isFirstTimeUpdatedServiceWorkerIsWaiting = |
|
21
|
|
|
event.wasWaitingBeforeRegister === false; |
|
22
|
|
|
console.log( |
|
|
|
|
|
|
23
|
|
|
'isFirstTimeUpdatedServiceWorkerIsWaiting', |
|
24
|
|
|
isFirstTimeUpdatedServiceWorkerIsWaiting |
|
25
|
|
|
); |
|
26
|
|
|
|
|
27
|
|
|
// Assumes your app has some sort of prompt UI element |
|
28
|
|
|
// that a user can either accept or reject. |
|
29
|
|
|
// const prompt = createUIPrompt({ |
|
30
|
|
|
// onAccept: async () => { |
|
31
|
|
|
// Assuming the user accepted the update, set up a listener |
|
32
|
|
|
// that will reload the page as soon as the previously waiting |
|
33
|
|
|
// service worker has taken control. |
|
34
|
|
|
wb.addEventListener('controlling', event => { |
|
|
|
|
|
|
35
|
|
|
window.location.reload(); |
|
36
|
|
|
}); |
|
37
|
|
|
|
|
38
|
|
|
// Send a message telling the service worker to skip waiting. |
|
39
|
|
|
// This will trigger the `controlling` event handler above. |
|
40
|
|
|
// Note: for this to work, you have to add a message |
|
41
|
|
|
// listener in your service worker. See below. |
|
42
|
|
|
wb.messageSW({ type: 'SKIP_WAITING' }); |
|
43
|
|
|
// }, |
|
44
|
|
|
|
|
45
|
|
|
// onReject: () => { |
|
46
|
|
|
// prompt.dismiss(); |
|
47
|
|
|
// }, |
|
48
|
|
|
// }); |
|
49
|
|
|
}); |
|
50
|
|
|
|
|
51
|
|
|
wb.register(); |
|
52
|
|
|
} |
|
53
|
|
|
|
This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.
To learn more about declaring variables in Javascript, see the MDN.