Tom
Tom

Reputation: 12659

Chrome extension to load a page and inject code

I am trying to create a simple extension which will load a given page and inject code once the page has loaded.

I came up with the following, am I doing this the right way?

background.js

    chrome.tabs.getCurrent(function (tab) {
      chrome.tabs.update(tab.id, {url: "http://www.EXAMPLE.COM"});
    });

    chrome.tabs.onUpdated.addListener(function(tabId , info) {
        if (info.status == "complete") {
                 chrome.tabs.executeScript(null, {file: "content_script.js"});
        }
    });

Upvotes: 0

Views: 306

Answers (1)

Xan
Xan

Reputation: 77482

Quoting chrome.tabs documentation for chrome.tabs.getCurrent:

Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).

To grab the currently active tab, you should instead use chrome.tabs.query:

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
  // Do something with tabs[0]
});

Alternatively, if you're reacting to user input, like a click on the browser action, you're already supplied the current tab:

chrome.browserAction.onClicked.addListener(function(tab){
  // "tab" is the current active tab
});

Instead of grabbing an already-open tab, you can simply create a new one (depends on what you're trying to achieve, of course):

chrome.tabs.create({url: "http://www.EXAMPLE.COM"});

Your listener will try to inject the content script into the current tab (you used null) whenever any tab finishes loading, not just the one you created. It's safer to do so from create/update callbacks, i.e.

chrome.tabs.update(tab.id, {url: "http://www.EXAMPLE.COM"}, function(tab){
  chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
});

Note: you don't have to worry that the page did not finish loading at this point. executeScript obeys the run_at parameter, which defaults to "sometime after DOM is loaded".

Upvotes: 1

Related Questions