0

Need your help please. I want to use the web starter kit on a own build php mvc framework. A part of the web starter kit is the use of a service worker.

In my root folder (called public in my case) i have the service worker file and i register it like the reconommend why like this:

if ('serviceWorker' in navigator &&
    (window.location.protocol === 'https:' || isLocalhost)) {
    navigator.serviceWorker.register('service-worker.js')
        .then(function(registration) {
....

If i try to call the root (index.php) page it works well. But if i try to call any route, the service worker will be called twice and one gives me an error and the second works fine. I found out, that first try with the thrown error just add the service-worker.js on my controller path.

For example, if I try to open mydomain/controller i get an error, that the mydomain/controller/service-worker.js could not found. Sure, there inst any.

Have one of you an idea, how to set that the service-worker will be called only in the root??

Hope, you can help and thank you very much

michiman
  • 35
  • 7

1 Answers1

2

The problem is coming from here:

navigator.serviceWorker.register('service-worker.js')

You tell the browser to fetch the file service-worker.js but without defining any folder. This will make the browser look for the file at a path relative to the current URL. When you are on domain.com/ the relative path becomes domain.com/service-worker.js but when you are on domain.com/controller, the relative path becomes domain.com/controller/service-worker.js

To work around this, you can either use a base tag

<base href="domain.com"/>

This will tell the browser that any relative path should be relative to that path instead of current path.

Another way could also be to simply use an absolute path to point to your service-worker.js

navigator.serviceWorker.register('/service-worker.js');
Salketer
  • 14,263
  • 2
  • 30
  • 58
  • An interesting read: https://stackoverflow.com/questions/21306512/difference-between-relative-path-and-absolute-path-in-javascript – Salketer Aug 28 '17 at 12:41