如何在 Chrome 扩展中使用内容脚本文件注入 CSS? [英] How to inject CSS using content script file in Chrome extension?

查看:73
本文介绍了如何在 Chrome 扩展中使用内容脚本文件注入 CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

I found similar question about injecting CSS, but I encountered a problem while using code from accepted answer. Here's my script.js contents:

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:

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

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.

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

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

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

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

推荐答案

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

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

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

<小时>

另请参阅程序化注入".和 insertCSS().

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

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

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

这篇关于如何在 Chrome 扩展中使用内容脚本文件注入 CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆