我正在尝试在内容脚本和扩展之间传递消息
以下是我在content-script中拥有的内容
chrome.runtime.sendMessage({type: "getUrls"}, function(response) {
console.log(response)
});
在背景脚本中,我有
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "getUrls"){
getUrls(request, sender, sendResponse)
}
});
function getUrls(request, sender, sendResponse){
var resp = sendResponse;
$.ajax({
url: "http://localhost:3000/urls",
method: 'GET',
success: function(d){
resp({urls: d})
}
});
}
现在,如果我在getUrls
函数中的ajax调用之前发送响应,响应将被成功发送,但是在ajax调用的成功方法中,当我发送响应时,它没有发送它,当我进入调试时,我可以看到sendResponse
函数的代码中的端口为空。
发布于 2014-05-03 01:57:38
公认的答案是正确的,我只是想添加示例代码来简化这一点。问题是API (在我看来)设计得不好,因为它迫使我们开发人员知道特定的消息是否将被异步处理。如果您处理许多不同的消息,这将成为一项不可能完成的任务,因为您永远不知道在某个函数内部,传入的sendResponse是否会被称为异步函数。请考虑以下内容:
chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
if (request.method == "method1") {
handleMethod1(sendResponse);
}
我如何才能知道handleMethod1
内部的调用是否是异步的?修改handleMethod1
的人怎么知道它会通过引入一些异步的东西来破坏调用者呢?
我的解决方案是:
chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
var responseStatus = { bCalled: false };
function sendResponse(obj) { //dummy wrapper to deal with exceptions and detect async
try {
sendResponseParam(obj);
} catch (e) {
//error handling
}
responseStatus.bCalled= true;
}
if (request.method == "method1") {
handleMethod1(sendResponse);
}
else if (request.method == "method2") {
handleMethod2(sendResponse);
}
...
if (!responseStatus.bCalled) { //if its set, the call wasn't async, else it is.
return true;
}
});
这会自动处理返回值,而不管您选择如何处理消息。请注意,这里假设您永远不会忘记调用响应函数。还请注意,铬可以为我们自动完成这项工作,我不明白他们为什么不这样做。
发布于 2017-06-11 22:02:35
你可以使用我的库https://github.com/lawlietmester/webextension在Chrome和FF中通过火狐的方式工作,而不需要回调。
您的代码将如下所示:
Browser.runtime.onMessage.addListener( request => new Promise( resolve => {
if( !request || typeof request !== 'object' || request.type !== "getUrls" ) return;
$.ajax({
'url': "http://localhost:3000/urls",
'method': 'GET'
}).then( urls => { resolve({ urls }); });
}) );
https://stackoverflow.com/questions/20077487
复制相似问题