javascript 为 chrome 扩展注入 CSS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9118402/
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-10-26 05:39:17  来源:igfitidea点击:

Inject CSS for chrome extension

javascripthtmlcssgoogle-chrome

提问by Jacques Blom

I am quite new to Chrome Extension development. I know it is possible to inject CSS. But is it possible to inject it for a specific URL. For example, whenever I visit google.com, the CSS will be injected.

我对 Chrome 扩展程序开发很陌生。我知道可以注入 CSS。但是是否可以为特定的 URL 注入它。例如,每当我访问 google.com 时,都会注入 CSS。

Thanks for the help! :)

谢谢您的帮助!:)

回答by Maxime Kjaer

Well, you have 2 options, programmatic injection and content scripts. The names might sound really complicated and frightening, but don't worry ;)

好吧,您有 2 个选项,程序化注入和内容脚本。这些名字听起来可能非常复杂和可怕,但别担心;)

Content Scriptswill inject themselves automatically when the page is loaded. All you need to do (apart from writing the script), is to specify something like this in your manifest.json:

加载页面时,内容脚本将自动注入自己。所有你需要做的(除了编写脚本)就是在你的 manifest.json 中指定这样的东西:

{
  "name": "My extension",
  "version": "1.0",
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": ["http://www.google.com/"], //where your script should be injected
      "css": ["css_file.css"] //the name of the file to be injected
    }
  ]
}

This should inject the CSS every time you load google.com

这应该在你每次加载 google.com 时注入 CSS

Your other option is to use Programmatic Injection. This can be useful if you want to inject the code only sometimes, usually from a background page. To do this, you can use insertCSS(). In that case, you'd need a host permissionin your manifest:

您的另一个选择是使用Programmatic Injection。如果您只想在某些时候(通常是从后台页面)注入代码,这会很有用。为此,您可以使用insertCSS()。在这种情况下,您需要清单中的主机权限

{
  "name": "My extension",
  "version": "1.0",
  "manifest_version": 2,
  "background_page": "myBackground.html", //if you want to inject it from a background page
  "permissions": [
    "background", //if you want to inject it from a background page
    "http://www.google.com/" // host permission to google
  ]
}

Good Luck!

祝你好运!