2014-09-06 59 views
0

我正在做一个扩展名为chrome,我想从内容脚本发送一条消息到后台脚本,请求发回一个var。就像这样:内容脚本不会收到我发送的对象

contentscript.js --> ask for var --> background.js 
              | 
contentscript.js <-- give var <------------ 

这是文件:

// contentscript.js 

'use strict'; 

function canGo() { 
    chrome.runtime.sendMessage({ message: 'go' }, function(response) { 
    return response.go; 
    }); 
} 

console.log(canGo()); // undefined 

// background.js 

'use strict'; 

var go = false; 

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
    if (request.message == 'go') { 
     sendResponse({ go: go }); 
    } 
    } 
); 

所以问题是,功能canGo返回undefined。我找不到原因。感谢您的帮助!

回答

1

chrome.runtime.sendMessage是异步的。

您的函数canGo()将在发送消息后立即终止,并且稍后将异步调用回调。您不能立即使用响应,您必须在回调中使用它。

function canGo() { 
    chrome.runtime.sendMessage({ message: 'go' }, function(response) { 
    console.log(response.go); 
    if(response.go) { /* ... */ } 
    else { /* ... */ } 
    }); 
} 
+0

谢谢,我不知道! – DennisvB 2014-09-06 10:14:05

相关问题