Skip to content

Instantly share code, notes, and snippets.

@johncovv
Last active October 31, 2020 21:28
Show Gist options
  • Save johncovv/4b891ef9f5d54ed9a13e00ac925bd980 to your computer and use it in GitHub Desktop.
Save johncovv/4b891ef9f5d54ed9a13e00ac925bd980 to your computer and use it in GitHub Desktop.
Creating a customized ServiceWorker for React and inserting push notification listener event

Custom ServiceWorker for React

These settings were made to integrate custom functions with the service worker.

Configuration to do before using the workbox

Go to the serviceWorker file in the project and make the following change.

    const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
    // to 
    const swUrl = `${process.env.PUBLIC_URL}/sw.js`;
{
"scripts": {
"build-sw": "node ./src/sw-build.js",
"clean-cra-sw": "rm -f build/precache-manifest.*.js && rm -f build/service-worker.js",
"build": "react-scripts build && yarn build-sw && yarn clean-cra-sw",
},
"dependencies": {
"workbox-build": "^5.1.4"
}
}
const workboxBuild = require('workbox-build');
const buildSw = () => {
// NOTE: This should be run *AFTER* all your assets are built
return workboxBuild
.injectManifest({
swSrc: 'src/sw-template.js', // custom sw template
swDest: 'build/sw.js', // this will be created in the build step
globDirectory: 'build',
globPatterns: [
'**/!(service-worker|precache-manifest.*).{js,css,html,png,jpg,jpeg,svg,ttf}',
'**/js.*.txt',
],
})
.then(({ count, size, warnings }) => {
// Optionally, log any warnings and details.
warnings.forEach(window.console.warn);
window.console.log(
`${count} files will be be preached, totaling ${size} bytes.`,
);
});
};
buildSw();
if ('function' === typeof importScripts) {
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js',
);
// create a listener for the SW push event
self.addEventListener('push', (event) => {
const parsed = JSON.parse(event.data.text());
const { title, description, link } = parsed;
self.registration.showNotification(title, {
icon: './logo.png',
body: description,
data: { link }
});
});
const location = self.location.host;
// what will be done after the user clicks on the notification
self.addEventListener('notificationclick', (event) => {
clients.openWindow(`${location}/${event.notification.data.link}`);
event.notification.close();
});
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
if (workbox) {
// workbox.core.clientsClaim();
/* injection point for manifest files. */
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);
/* custom cache rules*/
workbox.routing.registerNavigationRoute(
workbox.precaching.getCacheKeyForURL('/index.html'),
{
blacklist: [/^\/_/, /\/[^\/]+\.[^\/]+$/],
},
);
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg)$/,
new workbox.strategies.CacheFirst({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
}),
);
} else {
console.log('Workbox could not be loaded. No Offline support');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment