2

I know how to inject CSS into specified URLS using this method https://stackoverflow.com/a/7619104/1157283

However, what if I only want it to be injected into these pages when a browser action is clicked? I was reading about programmatic injection http://developer.chrome.com/extensions/content_scripts.html#pi and that makes it seem that you would have to get the tabIDs of all the pages you want to inject the CSS into, and then loop over them to inject the CSS for each tabID?

Is this what's required or am I completely off the mark here? It seems like it should be more straightforward to do than what I'm suggesting. Thanks!

Community
  • 1
  • 1
Ken
  • 530
  • 4
  • 11
  • 30

1 Answers1

3

Fear not my friend, here's a proper solution to your problem.

manifest.json We are going to specify the urls we want to inject the css to, as well as the tabs in the permissions directive.

"permissions":[
  "tabs",
  "https://google.com.mx/*"
],

background.js Add up the proper onClick listener.

chrome.browserAction.onClicked.addListener(browserListener);

And the listener looks like this

var browserListener = function(tab) {
    var regexPage = new RegExp(/https:\/\/www.google.com.mx\//); // We use a regular expresion to check which page was given.
    var match = regexPage.exec(tab.url); // We then check if the given page matches our expression.
    // If it matches and the status of the tab is complete...
    if(match && tab.status === 'complete') {
        //We insert the css
        chrome.tabs.insertCSS(tab.id, {
            file: "css/test.css"
        });
    }
}

You can skip the matching section if you ask permissions to all page with https://*/* in the permissions directive. This gives you more flexibility over content scripts, which they are triggered through matching only; just remember that as with any CSS, you need to specify proper rules that override of the ones of the page in order to see the changes, which most of the time means using the important! tag in your css.

jjperezaguinaga
  • 2,472
  • 14
  • 20