Chrome extension - inject css to pages upon browser action clicked

I know how to inject CSS into specified URLS using this method http://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!

Answers


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.


Need Your Help

foreach multidimensional array

php arrays foreach multidimensional-array

How do i loop through the following array with a foreach, so it gets printed like this:

PHP is adding slashes to characters when inserting into MySQL

php html mysql security filtering

When a ' is typed into a text field for example, PHP puts a \ before it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.