带有 webpack style-loader 的 Chrome 扩展程序找不到样式目标

nmu*_*nmu 4 css google-chrome-extension webpack webpack-style-loader firefox-addon-webextensions

我一直在开发的 chrome 扩展在 Firefox 上运行良好,但每当我尝试在 chrome 上运行它时,webpackstyle-loader都会抛出此错误:

Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.

一旦我删除了 css 导入,扩展就会运行,但我需要扩展的 css。

nmu*_*nmu 8

由于某种原因,如果您在清单中指定您的扩展程序应在以下位置运行document_start

"content_scripts": [
    {
      "run_at": "document_start",
      "matches": // ...
      "js": // ...
    }
  ],
Run Code Online (Sandbox Code Playgroud)

<head>在 Firefox 上,这将在构建后运行,因此style-loader将成功注入样式。但是,根据Chrome 的文档,将在构建任何其他 DOM 或运行任何其他脚本之前document_start注入 ” 。

所以我认为style-loader无法将 css 注入到<head>chrome 中,因为在文档启动时它尚未构建。

TL;DR:更改"document_start""document_idle"

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://*.nytimes.com/*"],
      "run_at": "document_idle",
      "js": ["contentScript.js"]
    }
  ],
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这可能会导致 FOUC,因此更好的解决方案可能是在样式加载器选项中指定 `insertInto: 'html'` ,它将样式元素直接附加到 document.documentElement 下。 (4认同)