javascript - Chrome 扩展消息传递 : response not sent

标签 javascript google-chrome google-chrome-extension google-chrome-app

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

这是我在内容脚本中的内容

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 函数的代码中的端口为空。

最佳答案

来自 the documentation for chrome.runtime.onMessage.addListener :

This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

所以你只需要在调用getUrls之后加上return true;,表示你将异步调用响应函数。

关于javascript - Chrome 扩展消息传递 : response not sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20077487/

相关文章:

javascript - 使用谷歌地图(或其他一些网络和移动平台)为 6000 多个位置放置标记

javascript - 用 jquery 停止 youtube 视频?

javascript - html post 和 js http.post 的区别

google-chrome - 将顶级域指向 url 的最佳方法是什么?

javascript - 将元素从一个列表复制到另一个

javascript - mdl-menu material-design-lite 中的 mdl-textfield

javascript - CHROME ext/app - 单击即可下载图像

javascript - Chrome : Error in event handler for runtime. onMessage

javascript - 在 chrome.tts.speak 中回调?

javascript - Chrome 扩展程序可检查链接并重定向到另一个网站