How to register the work service area of ​​one directory above where service_worker.js is located

MY directories are as follows.

public_html/ sw/ 

"sw /" is where I want to put all the working services, but then these service workers have an area for all the files in "public_html /".

Js

 <script> if ('serviceWorker' in navigator) { navigator.serviceWorker.register('sw/notifications.js', { scope: '../sw/' }).then(function(reg) { // registration worked console.log('Registration succeeded. Scope is ' + reg.scope); }).catch(function(error) { // registration failed console.log('Registration failed with ' + error); }); }; </script> 

How to resolve this scope?

+6
source share
2 answers

The maximum area for the worker, where he is . This means that you cannot register a single service worker located in /sw/ in scope: '/public_html/' unless you include the special Service-Worker-Allowed header set to the new maximum area for your worker.

To summarize, if you can add this header when servicing a service worker, set it as follows:

 Service-Worker-Allowed: /public_html/ 

If not, you should put sw in a specific place above the area.

+12
source

Change the scope property of the registration parameters object (the second parameter navigator.serviceWorker.register() ) to the URL at which you want the work service to be enabled. In your case, it could be ../public_html .

 // ... navigator.serviceWorker.register('sw/notifications.js', { scope: '../public_html/' }) // ... 

This parameter will default to ./ (relative to the ServiceWorker script) if the options object is not specified or does not have the scope property.

In addition, setting scope with any origin other than the current source will reject Promise registration with the exception of SecurityError .


Literature:

https://www.w3.org/TR/service-workers/#navigator-service-worker-register

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register#Parameters

+4
source

All Articles