1
votes

I dont know if i am doing this right or there is another way of doing it. I have a service worker for caching and i need to implement Firebase Cloud messaging too which requires a service worker. My first service worker is in the root of my project and i have this in it.

importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');
if (workbox) {
  workbox.precaching.precacheAndRoute([
  {
    "url": "icon-128x128.png",
    "revision": "af75a93ca2c343f1129dd7ee02fd4da7"
  },
  {
...
 }
]);



workbox.routing.registerRoute(
 /^\/$/,
  new workbox.strategies.NetworkFirst({
    cacheName: 'static-resources',
  })
);

workbox.routing.registerRoute(
 /^\/([^/]+\.htm)$/,
  new workbox.strategies.NetworkFirst({
    cacheName: 'static-resources',
  })
);


/**

  workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);
**/

  workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);




workbox.routing.registerRoute(
  // Cache image files.
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  // Use the cache if it's available.
  new workbox.strategies.CacheFirst({
    // Use a custom cache name.
    cacheName: 'image-cache',
    plugins: [
      new workbox.expiration.Plugin({
        // Cache only 50 images.
        maxEntries: 50,
        // Cache for a maximum of a week.
        maxAgeSeconds: 7 * 24 * 60 * 60,
      })
    ],
  })
);
 console.log(`Yay! Workbox is loaded ????`);

} else {
  console.log(`Boo! Workbox didn't load ????`);
}

Now i also need service worker for FCM which should have this in it

importScripts('https://www.gstatic.com/firebasejs/4.13.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.13.0/firebase-messaging.js');

if (firebase) {

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
   'messagingSenderId': '14******4'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/icon-128x128.png'
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});
}

I combined them into one service worker but there seem to be a problem with that as it registers sw.js which is the name of the service worker i have and also tries to register firebase-messaging-sw.js unsuccessfuly since i even dont have the file.

From the doc it says

One subtlety with the register() method is the location of the service worker file. You'll notice in this case that the service worker file is at the root of the domain. This means that the service worker's scope will be the entire origin. In other words, this service worker will receive fetch events for everything on this domain. If we register the service worker file at /example/sw.js, then the service worker would only see fetch events for pages whose URL starts with /example/ (i.e. /example/page1/, /example/page2/).

Now since it seems i need to have the service worker for caching and fcm in the root directory. How to i go about this?

I have this to register the service worker

<script>
  if ('serviceWorker' in navigator) {
     console.log('Service Worker is supported');
    window.addEventListener('load', () => {
      navigator.serviceWorker.register("/sw.js")
        .then(registration => {

          console.log(`Service Worker registered! Scope: ${registration.scope}`);
        })
        .catch(err => {
          console.log(`Service Worker registration failed: ${err}`);
        });
    });
  }
</script>
1
You can definitely combine them. You're not showing the code that registers your SW. Please add it to your q. - pate

1 Answers

1
votes

Well i just renamed my service worker file to firebase-messaging-sw.js for both workers and it registers both. It works that way for me.