diff --git a/.gitignore b/.gitignore index 3849d2e..dc31f92 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /node_modules /*.log +.idea/ \ No newline at end of file diff --git a/README.md b/README.md index 64fc9c6..daaf1ab 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,56 @@ serviceWorker.register({ }); ``` +### 3. Check for service worker update and activation service worker in other tabs + +In your main js file (`App.js`), you you can add specific behavior: + +``` + componentDidMount() { + if ('serviceWorker' in navigator) { + // Reload page after message from worker (if sw activated in another tab) + navigator.serviceWorker.addEventListener('message', function(event){ + if(event.data === 'reloadPage') { + window.location.reload(); + } + }); + + // Check for sw updates every second. You can change this interval. + // Don't forget to clear the interval in the componentWillUnmount + this.intervalSW = setInterval(() => navigator.serviceWorker.getRegistrations() + .then(registrationsArray => { + // Check for update service worker + if (registrationsArray && registrationsArray[0]) { + registrationsArray[0].update(); + } else { + console.error("serviceWorker: getRegistrations empty!") + } + }), 1000) + } else { + console.error("Browser does not support serviceWorker!") + } + } +``` + +### Check if the service worker is already waiting. + +``` + navigator.serviceWorker + .register(swUrl) + .then(registration => { + if(registration.waiting && registration.active) { + // The page has been loaded when there's already a waiting and active SW. + // This would happen if skipWaiting() isn't being called, and there are + // still old tabs open. + if(config && config.onUpdate) { + config.onUpdate(registration); + } + } + // ... + }) + // ... +``` + ## Options ### textContent diff --git a/inject-workbox-refresh.js b/inject-workbox-refresh.js index 394cc99..9985882 100644 --- a/inject-workbox-refresh.js +++ b/inject-workbox-refresh.js @@ -12,7 +12,18 @@ const fs = require("fs-extra"); const codeToAppend = ` self.addEventListener('message', function handleSkipWaiting(event) { - if (event.data === 'skipWaiting') { self.skipWaiting(); } + if (event.data === 'skipWaiting') { + clients.matchAll({includeUncontrolled: true}).then(function(clients) { + // Loop over all available clients + clients.forEach(function(client) { + // No need to update the tab that sent the data + if (client.id !== event.source.id ) { + client.postMessage('reloadPage') + } + }) + }) + self.skipWaiting(); + } }); `;