I was going through the Chrome extension "Getting started guide":
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?
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 + '";'
});
};
});