Skip to content Skip to sidebar Skip to footer

Chrome.tabs.executescript - Tabs Are Not Defined

I am trying to write a chrome extension that has a button called 'btn3'. When I click on that button in the chrome extension (popup.html), it will click a button on the webpage. Th

Solution 1:

the error of "tabs are not defined"

tabs[0] - you need to find it. Your script is executed in the context of popup.html. I hope popup.html contain

<head>
...
    <scriptsrc="popup.js"></script></head>

and

Script of the button in chrome extension window

is from popup.js. And you never try to run code inside popup.html.

So, in this context no one knows about tabs[0]. You need to ask chrome which window and which tab is active now. It can be as ShwetaM wrote, or like this from samples

chrome.windows.getCurrent(function (currentWindow) {
    chrome.tabs.query({ active: true, windowId: currentWindow.id }, function (activeTabs) {
        activeTabs.map(function (tab) {
            chrome.tabs.executeScript(tab.id, { file: 'content_script.js', allFrames: false });
        });
    });
});

or you can try without the tab.id,

chrome.tabs.executeScript({file:'content_script.js',allFrames:false});

because in this case the script will run in the active tab of the current window

When you specify in Manifest.json the "content_scripts": script will be executed when you create a tab and every refresh. I'm not sure, but maybe before loading the DOM. However, you should not specify the "content_scripts": in Manifest.json, because this content script's code will be always injected

Also you must be sure that the active tab contains a button that you are looking for. Use console.dir for some object, especially arguments in a function; console.log for some text; debugger for happy debugging.

Solution 2:

you can just remove the parameter "tabs[0]"

integer(optional) tabId The ID of the tab in which to run the script; defaults to the active tab of the current window.

https://developer.chrome.com/extensions/tabs#method-executeScript

Solution 3:

Try this:

sendInMail = function(){
  chrome.tabs.query({
                active: true,
                currentWindow: true
            }, function(tabs) {
    chrome.tabs.executeScript(tabs[0], {file: "content_script.js"});

  });

}

Post a Comment for "Chrome.tabs.executescript - Tabs Are Not Defined"