16

MY directories are as follows.

public_html/
sw/

The "sw/" is where I want to put all service workers, but then have those service workers with a scope to 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 do I allow this sort of scope?

Relm
  • 7,923
  • 18
  • 66
  • 113

2 Answers2

29

The max scope for a service worker is where it is located. This means you can not register one service worker located at /sw/ in scope: '/public_html/' unless you include a special header Service-Worker-Allowed set to the new max scope for your service worker.

Summarizing, if you can add this header when serving the service worker, set it as follows:

Service-Worker-Allowed: /public_html/

If not, you must place the sw at some location above the scope.

Salva
  • 6,507
  • 1
  • 26
  • 25
  • 2
    For any other lost soul like me looking for where or how to add this header, it needs to be added on the back end. On the web server serving the service worker file, like this person demonstrates: https://stackoverflow.com/questions/49084718/how-exactly-add-service-worker-allowed-to-register-service-worker-scope-in-upp/49098917/ Meaning your service worker request should look like this: https://medium.com/dev-channel/two-http-headers-related-to-service-workers-you-never-may-have-heard-of-c8862f76cc60 – sgarcia.dev Dec 08 '19 at 03:44
4

Edit: As Salva's answer indicates, the max scope must be widened with the Service-Worker-Allowed header to allow the following to succeed.


Change the scope property of the registration options object (the second parameter of navigator.serviceWorker.register()) to the URL you would like the service worker to be scoped to. In your case, this may be ../public_html.

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

That parameter will default to ./ (relative to the ServiceWorker script) if the options object is not provided, or has no scope property.

Also, setting a scope with any origin other than the current origin will reject the registration Promise with a SecurityError exception.


References:

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

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

Robert K. Bell
  • 9,350
  • 2
  • 35
  • 50
  • 8
    This will throw an error stating the scope is outside of the allowed scope. You need to also set the header as per the other answer. – Redmega Jun 23 '17 at 15:10