【问题标题】:call sendMessage without responseCallback在没有 responseCallback 的情况下调用 sendMessage
【发布时间】:2013-05-25 08:41:43
【问题描述】:

我从弹出窗口向后台进程发送消息。反馈信号对我来说不是必需的。我可以不调用 sendResponse。

popup.js

window.onload = function(){
    chrome.extension.sendMessage('Hi, i opened');
}

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    console.log(request);
    console.log(sendResponse);
    // sendResponse not called
})

在 sendmessage responseCallback 可选函数developer.chrome.com/extensions/runtime.html#method-sendMessage的文档中

如果我不传输 responseCallback,请在此处发送响应。上面的代码打印出来了。

function (response) {
    if (port) {
        port.postMessage(response);
        port.destroy_();
        port = null;
      } else {
        // We nulled out port when sending the response, and now the page
        // is trying to send another response for the same request.
        handleSendRequestError(isSendMessage, responseCallbackPreserved,
                               sourceExtensionId, targetExtensionId);
      }
    }

在功能的端口被删除。不调用 sendResponse 肯定是内存泄漏

【问题讨论】:

  • 请阅读sendResponse的描述:“当你有响应时调用的函数(最多一次)。参数应该是任何JSON-ifiable对象。如果你有多个onMessage监听器在同一个文档中,那么只有一个人可以发送响应。当事件侦听器返回时,此函数无效,除非您从事件侦听器返回 true,以表明您希望异步发送响应(这将保持消息通道对另一端开放,直到调用 sendResponse)。”

标签: google-chrome google-chrome-extension


【解决方案1】:

据我了解,您想向 background.js 发送消息并且不希望收到回复。 如果我是正确的,那么您只需要发送一条消息并忘记 "sendResponse"。 让我给你看看。

内容,js

window.onload = function(){
   chrome.extension.sendMessage('Hi, i opened');
}

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  console.log(request);
  //console.log(sendResponse); // **this line is not needed**
  // just do what ever you want to do with the "request", it has the message
  // content.js sent.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多