且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

注入Chrome扩展的CSS

更新时间:2023-12-05 20:35:40

好吧,你有两个选项,程序化注入和内容脚本。这些名称可能听起来真的很复杂和可怕,但不要担心;)

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

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

Content Scripts will 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:

{
  "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
    }
  ]
}

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

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

您的其他选项是使用程序化注入
如果你只想注入代码,通常从后台页面,这可能是有用的。为此,您可以使用 insertCSS()。在这种情况下,您的清单中需要有主机权限

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 permission in your manifest:

{
  "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
  ]
}

祝你好运!