1

I was going through the Chrome extension "Getting started guide":

https://developer.chrome.com/extensions/getstarted

and one section mentions this code

chrome.tabs.executeScript(
    tabs[0].id,
     {code: 'document.body.style.backgroundColor = "' + color + '";'});
};

I am getting an undefined error on tabs[0].id. Now the API documentation states that chrome.tabs.Tab is accessible but I can't seem to get it. What am I doing wrong?

Dalton Cézane
  • 3,672
  • 2
  • 35
  • 60
kaminsky59
  • 95
  • 1
  • 11

2 Answers2

2

You must query the tabs.

If you want to execute the code in all tabs. You can use this code.

chrome.tabs.query({}, function(tabs) {
    var message = {foo: bar};
    for (var i=0; i<tabs.length; ++i) {
        chrome.tabs.executeScript(tabs[0].id, {
                code: 'document.body.style.backgroundColor = "' + color + '";'
            });
        };
    }
});

If you want to execute the code only in the current tab. You can use this code.

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.executeScript(tabs[0].id, {
            code: 'document.body.style.backgroundColor = "' + color + '";'
        });
    };
});
Aefits
  • 3,399
  • 6
  • 28
  • 46
0

Please check your manifest file, you'll need to give relevant permission in the manifest.json file as:

"permissions": ["activeTab"],

to grant access to the tabs API not given already

nitish173
  • 108
  • 7