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

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功能。


蝴蝶不菲
浏览 1122回答 4
4回答

磐石BedRock

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

撒科打诨

接受的答案是正确的,我只是想添加示例代码来简化这一点。问题是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;}});这将自动处理返回值,而不管您选择如何处理消息。请注意,这假设您永远不会忘记调用响应函数。另外要注意的是,铬可以为我们实现自动化,我不明白他们为什么不这样做。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript