Inject CSS for chrome extension

前端 未结 1 532
情深已故
情深已故 2021-02-02 13:23

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

相关标签:
1条回答
  • 2021-02-02 14:23

    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:

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

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

    Good Luck!

    0 讨论(0)
提交回复
热议问题