首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Chrome扩展消息传递:未发送响应

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

Stack Overflow用户
提问于 2013-11-20 01:00:01
回答 2查看 56K关注 0票数 157

我正在尝试在内容脚本和扩展之间传递消息

以下是我在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函数的代码中的端口为空。

EN

回答 2

Stack Overflow用户

发布于 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;
    }

});

这会自动处理返回值,而不管您选择如何处理消息。请注意,这里假设您永远不会忘记调用响应函数。还请注意,铬可以为我们自动完成这项工作,我不明白他们为什么不这样做。

票数 8
EN

Stack Overflow用户

发布于 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 }); });
}) );
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20077487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档