kaminsky59
kaminsky59

Reputation: 95

chrome.tabs.Tab is undefined from popup.js script

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?

Upvotes: 1

Views: 2714

Answers (2)

nitish173
nitish173

Reputation: 118

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

Upvotes: 0

Aefits
Aefits

Reputation: 3469

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 + '";'
        });
    };
});

Upvotes: 2

Related Questions