Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject CSS for chrome extension

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.

Thanks for the help! :)

like image 781
Jacques Blom Avatar asked Feb 02 '12 19:02

Jacques Blom


1 Answers

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!

like image 191
Maxime Kjaer Avatar answered Sep 30 '22 18:09

Maxime Kjaer