Skip to content

Instantly share code, notes, and snippets.

@GautamPanickar
Last active July 19, 2020 07:44
Show Gist options
  • Save GautamPanickar/7fc2fc7a21893c539ea4416420ce042c to your computer and use it in GitHub Desktop.
Save GautamPanickar/7fc2fc7a21893c539ea4416420ce042c to your computer and use it in GitHub Desktop.
Service worker with Google's Workbox for Angular App - SW file
import {precacheAndRoute} from 'workbox-precaching';
import {registerRoute} from 'workbox-routing';
import { ServiceWorkerHandler } from './sw-handlers';
declare const self: any;
/**
* ------------------------------------
* Service Worker Listeners
* ------------------------------------
*/
self.addEventListener('message', function (event) {
// If you want to communicate anything directly from the angular component to the service worker,
// this is the place to do that.
// For example, you are intercepting a post request in the service worker and you want the posted data.
// Actually service workers do not allow you to access the request body.
// But you can send the data over to service worker from the component using postMessage() API
// of service worker, and then listen to the message here. Cool! Isn't it?
});
/**
* To initialize the indexedDB
*/
function initIndexedDB(): IDBOpenDBRequest {
const open = indexedDB.open('swtest', 1);
open.onsuccess = evt => {
console.log('DB opened successfully');
open.result.createObjectStore('images');
};
open.onerror = evt => {
console.log('Error while opening DB');
};
return open;
}
const dbPromise = initIndexedDB();
const swHandler = new ServiceWorkerHandler(dbPromise);
/**
* ------------------------------------
* Router Matchers
* ------------------------------------
*/
const bgImagesMatcher = ({url, request, event}) => {
return url.href.indexOf('/files/bg_images/') >= 0;
};
/**
* ------------------------------------
* Route Registrations
* ------------------------------------
*/
/**
* Here is the background images route registration.
* This intercepts the calls for fetching background images.
*/
// registerRoute(
// bgImagesMatcher,
// swHandler.bgImagesDBHandler,
// 'GET'
// );
registerRoute(
bgImagesMatcher,
swHandler.bgImagesCacheHandler,
'GET'
);
// This is the place holder for injectManifest
precacheAndRoute(self.__WB_MANIFEST);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment