ServiceWorker Cache on Install

I’m trying to figure out how I can cache a dynamic page on install? My current page is /product/1/view

self.addEventListener('install', function (event) {
event.waitUntil('kiosk-assets').then(function (cache) {
            return cache.addAll([
                '/' // This is the problem it caches the origin path i need the current page cached. See register below

Here is how I register my worker. This is registered on /product/1/view

window.navigator.serviceWorker.register('/sw.js', {scope: `/product/${id}/view`})

I can change how I register if this could be a possibility.

I do not think, you can do that onInstall

At least not with the service worker by itself. For the simple reason that, while the service worker is being installed, it has No idea what clients it is controlling / will control.

Also, Even an active serviceworker has No control over the DOM.
Hence, It has no way of knowing what the current url is.

you can either cache the url on activate , and or a fetch event


you need the client to ping the worker, while it is installing it.

If caching the registering page strictly onInstall is all you need, then ,

Send a Message via postMessage from the page that registers the worker

if ( 'serviceWorker' in navigator ) {
navigator.serviceWorker.register( 'sw.js' )
    .then( function ( success ) {
        console.log( 'scope', success.scope );
        if ( success.installing ) {
            let sw = success.installing;
            sw.addEventListener( 'statechange', function ( event ) {
                if ( == 'installed' ) {
                    let loc = window.location.toString();
                    let message = {
                        action: 'cache',
                        location: loc
                    sw.postMessage( message );
            } )
    } );

And use the message event within the worker, to cache the url

You should probably use sw-precache library for static and dynamic caching of data.

Integrate it with you build environment (Gulp, Grunt, Webpack). Sw-precache serves all your static files and update it accordingly. sw-precache has the options of runtime-caching which fill fulfill your needs

You can learn about the library here –