简体   繁体   English

为chrome扩展注入CSS

[英]Inject CSS for chrome extension

I am quite new to Chrome Extension development. 我是Chrome Extension开发的新手。 I know it is possible to inject CSS. 我知道可以注入CSS。 But is it possible to inject it for a specific URL. 但是可以为特定的URL注入它。 For example, whenever I visit google.com, the CSS will be injected. 例如,每当我访问google.com时,都会注入CSS。

Thanks for the help! 谢谢您的帮助! :) :)

Well, you have 2 options, programmatic injection and content scripts. 好吧,你有两个选项,程序注入和内容脚本。 The names might sound really complicated and frightening, but don't worry ;) 名字可能听起来非常复杂和令人恐惧,但不要担心;)

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: 除了编写脚本之外,您需要做的就是在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 . 您的另一个选择是使用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() . 为此,您可以使用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
  ]
}

Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM