0

I was trying to implement web worker in a backbone.js project and I got the error message src/js/worker.js 404 (Not Found)

I created a worker.js file and I have the code below in the file

this.addEventListner('message', function(e){
   console.log('Message received: ', e.data);
});

And the below code sends message to the worker

let worker = new Worker('src/js/worker.js')
worker.postMessage('hello');

Can someone please let me know what I'm doing wrong? Thanks!

T J
  • 42,762
  • 13
  • 83
  • 138
Jemil Oyebisi
  • 633
  • 8
  • 10

1 Answers1

1

It appears, that you try loading ther service worker script from an insecure location. I recommend you serving you development pages from http://localhost to make your first steps with service workers. You will find a great "guidepost" at the "Is ServiceWorker Ready?" web site.

Make sure, that you:

You won't be able to load the service worker script from http or https protcols without a valid certificate. Serving you page from http://localhost is an exception; localhost is considered secure to make the development easier. See also the full list of "secure" origins as implemented in Chrome.

You will get the same error, if the file is missing or if the browser cannot load it from the protocol, which you used:

A bad HTTP response code (404) was received when fetching the script.
Failed to load resource: net::ERR_INVALID_RESPONSE
ServiceWorker registration failed:  TypeError: Failed to register a ServiceWorker:
  A bad HTTP response code (404) was received when fetching the script.

If the SSL certificate of your web site is invalid, including self-signed certificates, you will get the following error:

An SSL certificate error occurred when fetching the script.
Failed to load resource: net::ERR_CERT_DATE_INVALID
ServiceWorker registration failed:  DOMException: Failed to register a ServiceWorker:
  An SSL certificate error occurred when fetching the script.

If you use a self-signed certificate, you can install the SSL certificate of your "fake" CA as a trusted root certificate authority in your web browser or OS. The browser will not ask you for an exception in accessing your page any more and the service worker will load well.

If you use Chrome, you can use parameters --unsafely-treat-insecure-origin-as-secure and --allow-insecure-localhost to force the browser to load the service worker script from otherwise illegal origins. But do it only in your development environment. Not at the production web site.

Ferdinand Prantl
  • 5,281
  • 34
  • 35