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

RayfenWindspear picture RayfenWindspear · Jan 10, 2017 · Viewed 13.1k times · Source

According to the documentation for chrome.tabs.executeScript (MDN), the callback function accepts an "array of any result" result set from the execution of the script(s). How exactly do you use this to get results? All of my attempts end up with undefined being passed to the callback.

I have tried returning a value at the end of my content script, which threw a Uncaught SyntaxError: Illegal return statement. I tried using the optional code object argument {code: "return "Hello";} with no success.

I feel like I am not understanding what is meant by "The result of the script in every injected frame", in the documentation.

Answer

Makyen picture Makyen · Jan 10, 2017

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.