Ray*_*ear 5 javascript google-chrome google-chrome-extension firefox-addon-webextensions
根据chrome.tabs.executeScript(MDN)的文档,回调函数接受来自脚本执行的"任何结果数组"结果集.你究竟如何使用它来获得结果?我的所有尝试最终都undefined被传递给了回调.
我已经尝试在我的内容脚本的末尾返回一个值,它抛出一个Uncaught SyntaxError: Illegal return statement.我尝试使用可选的代码对象参数但{code: "return "Hello";}没有成功.
我觉得我不理解文档中"每个注入框架中脚本的结果"的含义.
Mak*_*yen 11
chrome.tabs.executeScript()从运行脚本的每个选项卡/框架返回一个带有"脚本结果"的数组.
"脚本的结果"是最后一个计算语句的值,它可以是函数返回的值(即IIFE,使用return语句).通常,console.log()如果您从Web控制台(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]);
}
Run Code Online (Sandbox Code Playgroud)
这将注入内容脚本来获得.innerText的<body>点击浏览器的操作按钮时.你需要得到activeTab许可.
作为这些产生的示例,您可以打开网页控制台(F12)并输入document.body.innerText;或(function (){return document.body.innerText;})();查看将返回的内容.
| 归档时间: |
|
| 查看次数: |
5925 次 |
| 最近记录: |