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.
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 (notconsole.log()
, but the results) if you executed the code/script from the Web Console (F12) (e.g. for the scriptvar foo='my result';foo;
, theresults
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:
This will inject a content script to get the
.innerText
of the<body>
when the browser action button is clicked. you will need theactiveTab
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.