Web worker importScripts DOMException 脚本加载失败

Web worker importScripts DOMException script failed to load

我正在尝试使用 importScripts

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

为 PWA 的服务工作者加载库,但不断获取

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

脚本文件在那里,内容类型正确,application/javascript,我也用 text/javascript 试过了。我的开发人员工具网络选项卡显示请求开始然后很快失败,没有机会访问服务器。通过 http 时状态代码为 (failed) net::ERR_CONNECTION_REFUSED,通过 https 时状态代码为 (failed) net::ERR_FAILED。任何帮助表示赞赏

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

我原来的post错了。 @kmanzana 指出 localhost 被认为是 "secure origin".

根据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.

我必须将 importScripts 移动到我的文件或安装处理程序的顶层,它起作用了