kmanzana
kmanzana

Reputation: 1198

Web worker importScripts DOMException script failed to load

I'm trying to use importScripts

self.addEventListener('fetch', event => {
  ...
  self.importScripts('idb.js');
  ...
}

to load a library for a service worker for a PWA but keep getting

DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': 
    The script at 'http://localhost:3000/idb.js' failed to load.

The script file is there, content type is correct, application/javascript, and I've tried it with text/javascript too. My developer tools network tab shows the request starting and then failing really quickly, not getting a chance to hit the server. The status code is (failed) net::ERR_CONNECTION_REFUSED when over http and (failed) net::ERR_FAILED over https. Any help appreciated

Upvotes: 6

Views: 8960

Answers (3)

Engineer
Engineer

Reputation: 8847

Also, if there is an import statement inside any of the scripts on which you are using importScripts(), you will get this error, and it will not immediately be clear why.

Upvotes: 4

kmanzana
kmanzana

Reputation: 1198

According to https://developers.google.com/web/updates/2018/10/tweaks-to-addAll-importScripts

Prior to Chrome 71, calling importScripts() asynchronously outside of the install handler would work. Starting with Chrome 71, those calls throw a runtime exception (unless the same URL was previously imported in an install handler), matching the behavior in other browsers.

I have to move importScripts to the top level of my file or my install handler and it works

Upvotes: 8

Justin Collins
Justin Collins

Reputation: 350

Based upon the link you provided, you are not running under HTTPS. You need a site under HTTPS to use a service worker.

My original post wrong. @kmanzana pointed out that localhost is considered a "secure origin".

Upvotes: 1

Related Questions