Javascript 内容脚本未接收我发送的对象
我正在制作一个chrome扩展,我想从一个内容脚本向一个后台脚本发送一条消息,请求返回一个var。像这样:Javascript 内容脚本未接收我发送的对象,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在制作一个chrome扩展,我想从一个内容脚本向一个后台脚本发送一条消息,请求返回一个var。像这样: contentscript.js --> ask for var --> background.js | contentscript.js <-- give var <------------ 及 所以问题是函数canGo返回未定义的。我不知道为什么。谢谢你的帮助 chrome.r
contentscript.js --> ask for var --> background.js
|
contentscript.js <-- give var <------------
及
所以问题是函数
canGo
返回未定义的。我不知道为什么。谢谢你的帮助 chrome.runtime.sendMessage是异步的
您的函数canGo()
将在发送消息后立即终止,稍后将异步调用回调。您不能立即使用响应,必须从回调中使用它
function canGo() {
chrome.runtime.sendMessage({ message: 'go' }, function(response) {
console.log(response.go);
if(response.go) { /* ... */ }
else { /* ... */ }
});
}
谢谢,我不知道!
// background.js
'use strict';
var go = false;
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message == 'go') {
sendResponse({ go: go });
}
}
);
function canGo() {
chrome.runtime.sendMessage({ message: 'go' }, function(response) {
console.log(response.go);
if(response.go) { /* ... */ }
else { /* ... */ }
});
}