等待chrome.extension.sendRequest

时间:2012-03-06 11:28:50

标签: javascript google-chrome

我想从background.html读取我的全局变量,我使用它:

chrome.extension.sendRequest()

我在我的计时器功能中运行此代码...每次它都返回我未定义。如果我在上面的函数中放了一条警告消息,那么它会显示我的变量..如果我没有使用alert()那么它是未定义的。那么我怎么能等待上面的函数返回正确的值,...我理解我需要等待响应...但我怎么能正确,我试着在上面的函数里面使用setInterval并没有帮助我。 如何从background.html读取我的全局值...我需要一段代码。

chrome.extension.sendRequest({cmd: "myvalue"}, function(response) {
     myglobalvalue = response;
  if(response==1){

   alert("response: "+response); // alert show me right value

             }
});

if(myglobalvalue)doFunc();  //myglobalvalue is undefenited

3 个答案:

答案 0 :(得分:1)

您可以使用chrome.extension.getBackgroundPage().varname

从background.html读取变量

答案 1 :(得分:0)

chrome.extension.sendRequest接受将使用响应数据触发的回调函数。

chrome.extension.sendRequest({ data: 'send data' }, function(response) {
  console.log(response);
  // the var has been returned and you can use it here or call another function.
});

答案 2 :(得分:0)

在这里:Chrome Extension Socket

我构建它以在弹出窗口和后台页面之间提供连续的双向通信。 “如何使用”部分告诉您该怎么做。只需在弹出窗口和后台页面中包含socket.js,就会自动为您创建连接。

只需使用:

Socket.postMessage(namespace, literal, method, [args]);

这将允许您触发可以使用数据回调的函数。

相关问题