Running an offline service worker and OneSignal in a PWA

265 Views Asked by At

I've got a PWA and I'm trying to run OneSignal (for web push notification subscriptions) and an offline service worker alongside each other. They both work on their own. I've tried a few iterations with varying levels of one working or the other. I've got a vague sense that the answer is that I need to merge the 2 service workers but I'm not 100% sure how to do this. Any insight or guidance on this would be appreciated.

This is the OneSignalSDKWorker.js script (as supplied by OneSignal)

importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');

This is my offline service worker script (as supplied by PWA builder)

importScripts("https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js");

const CACHE = "pwabuilder-offline";

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

workbox.routing.registerRoute(
  new RegExp('/*'),
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: CACHE
  })
);
1

There are 1 best solutions below

0
Richard McKechnie On

I got the functionality from both service workers working by adding / merging the PWA Builder offline service worker script into OneSignalSDKWorker.js like so:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
importScripts("https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js"); //This was the original line in this file

const CACHE = "pwabuilder-offline";

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

workbox.routing.registerRoute(
  new RegExp('/*'),
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: CACHE
  })
);

Then I initialised the service worker in the head of my html with the following:

<script>
    if (typeof navigator.serviceWorker !== 'undefined') {
        navigator.serviceWorker.register('OneSignalSDKWorker.js?v=2')
        .then(function(registration) {
        console.log('Service Worker registered with scope:', registration.scope);
        })
        .catch(function(error) {
        console.error('Service Worker registration failed:', error);
        });
    }
</script>
<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
<script>
    window.OneSignalDeferred = window.OneSignalDeferred || [];
    OneSignalDeferred.push(async function(OneSignal) {
        await OneSignal.init({
            appId: "<APP-ID>"
        });
    });
</script>