Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取executeScript中变量集的值_Javascript_Google Chrome_Google Chrome Extension_Scope_Return - Fatal编程技术网

Javascript 获取executeScript中变量集的值

Javascript 获取executeScript中变量集的值,javascript,google-chrome,google-chrome-extension,scope,return,Javascript,Google Chrome,Google Chrome Extension,Scope,Return,创建Google Chrome扩展时,我的代码必须保留在单独的javascript文件中: separate.js ----------- var x = "some dynamic value"; var y = "another dynamic value"; return x; 我想将此代码中的x值转换为包含在我的背景页中的代码: background.html ----------- <!DOCTYPE html> <html> <head>&l

创建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>

如何在separate.js中检索变量集(比如y)?有没有一种方法可以使用executeScript()获取脚本的返回值?

code.js
(由扩展注入)中,使用:


使用(位于
separate.js
)和
chrome.onRequest
(位于code.js)。我不确定如何实现这一点。你能展示一个使用上述上下文的示例吗?我已经发布了一个非常基本的示例,演示了如何使用这些方法。我看到了sendRequest和listener函数的工作方式以及它们应该驻留的位置,但我看不到上面是如何导致code.js将请求发送到separate.js的。separate.js的引用在哪里?
separate.js
是扩展的背景页面
background.html
的一部分。当在
code.js
中使用
…sendRequest(..)
时,后台会收到一个请求。这个请求可以通过定义一个侦听器(我的示例的最后一行)来捕获。
code.js
-----------
chrome.tabs.executeScript(null, {file:"separate.js"}, function() {});
var y = "variable to send";
function f_callback(response) {
    alert(response);
}
chrome.extension.sendRequest({y: y}, f_callback); //<-- Trigger
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);