不使用responseCallback调用sendMessage

时间:2013-05-25 08:41:43

标签: google-chrome google-chrome-extension

我将消息从弹出窗口发送到后台进程。反馈信号对我来说不是必需的。我可以不拨打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,请发送sendResponse。上面的代码打印出来。

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

,肯定会出现内存泄漏

1 个答案:

答案 0 :(得分:0)

根据我的理解,您希望向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.
});