【问题标题】:Obtaining the value of a variable set in executeScript获取executeScript中设置的变量的值
【发布时间】:2012-01-04 20:14:26
【问题描述】:

在创建 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() {});

我如何去检索一个在分开的.js 中设置的变量(比如,y)?有没有办法使用 executeScript() 来获取脚本的返回值?

【问题讨论】:

  • 使用chrome.sendRequestseparate.js)和chrome.onRequest(code.js)。
  • 我不确定如何实现这一点。你能举一个使用上述上下文的例子吗?
  • 我发布了一个非常基本的、简单的示例,演示了如何使用这些方法。

标签: javascript google-chrome google-chrome-extension scope return


【解决方案1】:

在你的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.jsbackground.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);

【讨论】:

  • 我看到了 sendRequest 和 listener 函数是如何工作的以及它们应该驻留在哪里,但我没有看到上述如何导致 code.js 将请求发送到 separate.js。对分离.js 的引用在哪里?
  • separate.js 是您扩展程序的背景页面 background.html 的一部分。在code.js使用...sendRequest(..)时,后台接收到一个请求。这个请求可以通过定义一个监听器来捕获(我的例子的最后一行)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 2023-03-21
  • 2013-04-08
相关资源
最近更新 更多