4

I am new to web development so sorry if I'm not clear with my question.

I am trying to make a PWA and am currently testing to see if my manifest and service worker are working. In my project, I have an index.html file which calls the file app.js, in which I try to register the service worker named serviceworker.js. Here is the segment of code where I try to register my service worker:

if('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/serviceworker.js')
  .then(function() {
    console.log('service worker registered');
  });
}
else {
  console.log('cannot register');
}

When I reload my page, my console displays "cannot register". To troubleshoot this, I wrote a line in the if clause to see if it was a problem with the condition itself. Turns out, Even by removing the if and else clauses and simply running the navigator.serviceWorker.register('/serviceworker.js') .then(function() { console.log('service worker registered'); }); segment of the code, the console displays an error say "cannot find property register". From what I understand, service workers do not work on all browsers, but I checked to see if it runs in Chrome (which is what I'm testing in) and it says that service workers are supported. Can someone please tell me why it isn't working? I'm currently using Version 80.0.3987.149 (Official Build) (64-bit) of Chrome. Alsi, I don't know if this is important, but I am using Node.js. Thanks in advance.

2
  • what does nodejs have to do with service-worker in a browser? Commented Mar 27, 2020 at 3:25
  • 2
    I didn't know if it had anything to do with node.js. I just put it thinking that it might. Commented Mar 27, 2020 at 3:29

1 Answer 1

4

Cannot comment because of low reputation, but check this & this out.

In short: Service workers requires the site using them to be served over HTTPS for security reasons, but have execptions for localhost.

Check this for how to serve your html file on localhost.

Not the answer you're looking for? Browse other questions tagged or ask your own question.