在创建 Google Chrome 扩展程序时,我有一些代码必须保留在单独的 javascript 文件中:
separate.js
-----------
var x = "some dynamic value";
var y = "another dynamic value";
return x;
我想从这段代码中获取 x 的值到我的后台页面中包含的代码中:
background.html
-----------
<!DOCTYPE html>
<html>
<head><script src="code.js"></script></head>
</html>
_
code.js
-----------
chrome.tabs.executeScript(null, {file:"separate.js"}, function() {});
如何在 separate.js 中检索变量集(例如,y)?有没有办法使用 executeScript() 来获取脚本的返回值?
最佳答案
在您的 code.js
(由您的扩展程序注入(inject))中,使用 chrome.extension.sendRequest
:
var y = "variable to send";
function f_callback(response) {
alert(response);
}
chrome.extension.sendRequest({y: y}, f_callback); //<-- Trigger
在separate.js
(在background.html
),使用chrome.extension.onRequest
:
function listener(o_request, o_sender, f_callback) {
// This function is triggered by the function, see above
alert(o_request.y); //<---y
f_callback("Done something"); //<-- Calls callback. Can only be done once!
}
chrome.extension.onRequest.addListener(listener);
关于javascript - 获取executeScript中设置的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733375/