为了账号安全,请及时绑定邮箱和手机立即绑定

Chrome扩展消息传递:响应未发送

Chrome扩展消息传递:响应未发送

蝴蝶不菲 2019-06-01 13:43:42
Chrome扩展消息传递:响应未发送我试图在内容脚本和扩展之间传递消息。以下是我的内容-脚本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})     }   });}现在,如果我在Ajax调用之前在getUrls函数中,响应被成功发送,但是在Ajax调用的成功方法中,当我发送响应时它没有发送它,当我开始调试时,我可以看到端口在下面的代码中为空sendResponse功能。
查看完整描述

4 回答

?
磐石BedRock

TA贡献1条经验 获得超0个赞

你好, 请问这个问题解决了吗? chrome.runtime.sendMessage应该怎么样才能接收到这个回调回来的参数?

查看完整回答
反对 回复 2019-09-21
?
撒科打诨

TA贡献1934条经验 获得超2个赞

接受的答案是正确的,我只是想添加示例代码来简化这一点。问题是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;}});

这将自动处理返回值,而不管您选择如何处理消息。请注意,这假设您永远不会忘记调用响应函数。另外要注意的是,铬可以为我们实现自动化,我不明白他们为什么不这样做。


查看完整回答
反对 回复 2019-06-01
  • 4 回答
  • 0 关注
  • 1115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信