Javascript 如何在 Chrome 扩展中使用内容脚本文件注入 CSS?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11553600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:17:23  来源:igfitidea点击:

How to inject CSS using content script file in Chrome extension?

javascriptgoogle-chrome-extensioncontent-script

提问by Roman

I'm trying to inject my CSS from JavaScript which is injected as content script:

我正在尝试从作为内容脚本注入的 JavaScript 注入我的 CSS:

"content_scripts": [
   {
      "matches": ["http://www.google.com/*"],
      "js": ["script.js"]
   }
],

I found similar questionabout injecting CSS, but I encountered a problem while using code from accepted answer. Here's my script.jscontents:

我发现了有关注入 CSS 的类似问题,但是在使用来自已接受答案的代码时遇到了问题。这是我的script.js内容:

var link = document.createElement("link");
link.href = chrome.extension.getURL("style.css");
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);

After I load some page this message appears in console:

加载某个页面后,此消息出现在控制台中:

Denying load of chrome-extension://phkgaaiaakklogbhkdnpjncedlbamani/fix.css. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

拒绝加载 chrome-extension://phkgaaiaakklogbhkdnpjncedlbamani/fix.css。资源必须在 web_accessible_resources 清单键中列出,以便由扩展程序之外的页面加载。

Is there any way to fix this? Or, maybe, some other way to inject a CSS from that JavaScript file?

有没有什么办法解决这一问题?或者,也许是从该 JavaScript 文件中注入 CSS 的其他方法?

Note: I can't include style sheet directly from manifest.

注意:我不能直接从清单中包含样式表。

回答by Brock Adams

You could add to the manifest's permissions field; See web_accessible_resources. So you would add this to the manifest:

您可以添加到清单的权限字段;请参阅web_accessible_resources。因此,您可以将其添加到清单中:

    , "web_accessible_resources": [
        "fix.css"
    ]


See also "Programmatic injection". and insertCSS().

另见“程序化注入”。和insertCSS()

For most applications, forget all that createElementcode and just add the CSS file to the manifest:

对于大多数应用程序,忘记所有createElement代码,只需将 CSS 文件添加到清单:

"content_scripts": [
   {
      "matches":    ["http://www.google.com/*"],
      "css":        ["fix.css"],
      "js":         ["script.js"]
   }
],

although I understand that you don't want to do that in this exact instance.

虽然我知道你不想在这个确切的例子中这样做。