How to prevent the same service worker from registering over multiple pages?

后端 未结 2 561
粉色の甜心
粉色の甜心 2020-12-10 12:09

I have a service worker script that is registering repeatedly over multiple site levels.

In other words the same service worker is registered for www.site.ca/, www.s

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 12:56

    According to MDN, ServiceWorkerContainer.register method takes a second parameter of options:

    Currently available options are:

    • scope: A USVString representing a URL that defines a service worker's registration scope; what range of URLs a service worker can control. This is usually a relative URL, and it defaults to '/' when not specified.

    As for your updated question, the W3C Service Workers WD says:

    A service worker registration of an identical scope url when one already exists in the user agent causes the existing service worker registration to be replaced.

    Therefore navigator.serviceWorker.register(url, {scope: '/'}).then(doSomething) should work.

    Problem is with the scope URL in your example:

    ./ should be /

提交回复
热议问题