简体   繁体   中英

How can I pass a parameter from Razor into the service worker file for a PWA?

I'm creating a PWA (Progressive Web App), and am registering my service worker in my view:

    if('serviceWorker' in navigator) {
        navigator.serviceWorker.register('@Url.Content("~/sw.js")', { scope: '@Url.Content("~/")' })
          .then(function(registration) {
            console.log('G081 Service Worker Registered');
          });
        navigator.serviceWorker.ready.then(function(registration) {
            console.log('G081 Service Worker Ready');
        });
    }

And one of the first things I do in my service worker is import the idb-keyval library, as follows:

(function () {
    "use strict";
    self.importScripts("/3971/lib/idb-keyval/idb-keyval-iife.min.js");
}());

All is is well with that. It's registered and running. However, you will notice in my self.importScripts function (in my service worker), I am hard-coding part of the path ( "3971/" ). I am doing this because of the branching strategy we use at my job. Every branch gets its own site on our test server (In my case it's 3971). As a result, I need to be able to tell my service worker to look in the sub-folder 3971 for the idb-keyval javascript file. If I don't tell it that, it looks in the parent folder and doesn't find it. And this will change again when we push to production. The app will then be at the site root, and will need to look for the javascript file without the "3971" sub-folder.

I am going to call this my scope folder. Essentially I need a way to tell my service worker which scope folder to use for resources. I'm doing something similar in my view page, as you see above, where I use Razor to serialize my scope folder to register my service worker:

navigator.serviceWorker.register('@Url.Content("~/sw.js")', { scope: '@Url.Content("~/")' })

Renders to:

navigator.serviceWorker.register('/3971/sw.js', { scope: '/3971/' }) // MY DYNAMIC BRANCH
// and ...
navigator.serviceWorker.register('/sw.js', { scope: '/' }) // PRODUCTION

Is there a way that I can pass a parameter into my service worker so that it knows which scope folder it is using? For example, can I do something like this:

navigator.serviceWorker.register('/3971/sw.js?scope=%2F3971%2F', { scope: '/3971/' }) // MY DYNAMIC BRANCH

And then in my service worker, consume that parameter and use it to get my resource(s)? Something like this:

(function () {
    "use strict";
    self.importScripts(param['scope'] + "lib/idb-keyval/idb-keyval-iife.min.js");
}());

您可以获取服务工作者路径的查询参数。

const scope = (new URLSearchParams(location.search)).get('scope');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM