6

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

0

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

1

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".

6 Comments

"Service workers are only available to "secure origins" (HTTPS sites, basically)...localhost is also considered a secure origin" from chromium.org/blink/serviceworker/service-worker-faq
I just checked to make sure and served this file over ngrok with https and I'm still seeing the same problem
Well TIL. What is the status code you receive when you fetch? Are you able to see the response when you directly navigate?
actually, status code was (failed) net::ERR_CONNECTION_REFUSED when over http and over https it is (failed) net::ERR_FAILED. I'm able to see the response with navigation or curl yes
Well I apologize. I attempted to recreate locally with both HTTPS and HTTP but I was unsuccessful.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.