在创建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()来获取脚本的返回值?
答案 0 :(得分:2)
在code.js
(由您的扩展程序注明)中,使用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);