chrome.tabs.executeScript(): 如何获取内容脚本的结果?

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

根据 documentation for chrome.tabs.executeScript (MDN),回调函数接受来自脚本执行的 "array of any result" 结果集。您究竟如何使用它来获得结果?我所有的尝试都以 undefined 被传递给回调结束。

我尝试在我的内容脚本末尾返回一个值,结果抛出了 Uncaught SyntaxError: Illegal return statement。我尝试使用可选代码对象参数 {code: "return "Hello";} 但没有成功。

我觉得我不明白文档中 "The result of the script in every injected frame" 的含义。

chrome.tabs.executeScript() returns 来自每个 tab/frame 的 Array 和 "the result of the script",其中脚本是 运行。

"The result of the script" 是最后一个求值语句的值,它可以是函数返回的值(即 IIFE,使用 return 语句)。通常,如果您从 Web 控制台执行 code/script ( F12)(例如,对于脚本 var foo='my result';foo;results 数组将包含字符串“my result”作为元素)。如果您的代码很短,您可以尝试从控制台执行它。

下面是一些示例代码,摘自 :

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]);
}

这将注入内容脚本以在单击浏览器操作按钮时获取 <body>.innerText。您将需要 activeTab 权限。

作为这些产生的例子,您可以打开网页控制台(F12)并输入document.body.innerText;(function (){return document.body.innerText;})();来查看将返回什么。