Skip to content
Advertisement

Relay information to the service worker on install

I have a PWA with multiple different languages and would like to cache only language specific files on install. I can’t find out a way to communicate the language to the service worker during install. Ideas on how I could do it?

My js code to initiate the service worker:

navigator.serviceWorker.register('../service-worker.js', { scope: '/' }).then((reg) => {
    console.log('Service worker registered successfully.', reg);
    registration = reg;
}).catch(function (e) {
    console.error('Error during service worker registration:', e);
});

My code in the service-worker.js:

self.addEventListener('install', function(event) {
    messageAllClients('Event-Install');
    // Perform install steps
    event.waitUntil(
        caches.open(CACHE_NAME).then(function(cache) {
            messageAllClients('Language detected by the service worker: '+language);
            messageAllClients('Pre-caching offline page');
            return cache.addAll(FILES_TO_CACHE);
        })
    );
    self.skipWaiting();
});

Advertisement

Answer

Variables can be relayed to the service worker during install via GET attributes, as @JeffPosnick pointed out in the comment.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement