chrome.tabs.executeScript(): How to get result of content script?

chrome.tabs.executeScript() returns an Array with “the result of the script” from each tab/frame in which the script is run.

“The result of the script” is the value of the last evaluated statement, which can be the value returned by a function (i.e. an IIFE, using a return statement). Generally, this will be the same thing that the console would display as the results of the execution (not console.log(), but the results) if you executed the code/script from the Web Console (F12) (e.g. for the script var foo='my result';foo;, the results array will contain the string “my result” as an element). If your code is short, you can try executing it from the console.

Here is some example code taken from another answer of mine:

chrome.browserAction.onClicked.addListener(function(tab) {
    console.log('Injecting content script(s)');
    //On Firefox document.body.textContent is probably more appropriate
    chrome.tabs.executeScript(tab.id,{
        code: 'document.body.innerText;'
        //If you had something somewhat more complex you can use an IIFE:
        //code: '(function (){return document.body.innerText;})();'
        //If your code was complex, you should store it in a
        // separate .js file, which you inject with the file: property.
    },receiveText);
});

//tabs.executeScript() returns the results of the executed script
//  in an array of results, one entry per frame in which the script
//  was injected.
function receiveText(resultsArray){
    console.log(resultsArray[0]);
}

This will inject a content script to get the .innerText of the <body> when the browser action button is clicked. you will need the activeTab permission.

As an example of what these produce, you can open up the web page console (F12) and type in document.body.innerText; or (function (){return document.body.innerText;})(); to see what will be returned.

Leave a Comment