chrome.runtime.onmessage和chrome.runtime.port onmessage事件之间的区别

时间:2018-05-10 20:01:55

标签: google-chrome-extension

我的以下contentscript.js只收到chrome.runtime.onMessage.addListener的消息,但没有收到port.onMessage.addListener

的消息
             console.log("loaded");
              var port = chrome.runtime.connect({name: "knockknock"});
              port.postMessage({joke: "Knock knock"});
              port.onMessage.addListener(function(msg) {
              port.postMessage({answer: "Madame... Bovary"});
              });
              chrome.runtime.onMessage.addListener(function (msg, sender, response) {
              console.log("cs:on message ");
              });

I send the following message from my backgroundscript.js:



             chrome.tabs.query({
                  active: true,
                  currentWindow: true
              }, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
                  console.log("message sent");
                });
              });

为什么我的port.onMessage.addListener在初始化时没有被触发。

1 个答案:

答案 0 :(得分:0)

来自https://developer.chrome.com/extensions/messaging

  

为了处理传入连接,您需要设置一个   runtime.onConnect事件侦听器。这看起来与内容相同   脚本或扩展页面。当分机的另一部分呼叫时   “connect()”,此事件与runtime.Port对象一起被触发   您可以使用通过连接发送和接收消息。   以下是响应传入连接的样子:

chrome.runtime.onConnect.addListener(function(port) {
  console.assert(port.name == "knockknock");
  port.onMessage.addListener(function(msg) {
    if (msg.joke == "Knock knock")
      port.postMessage({question: "Who's there?"});
    else if (msg.answer == "Madame")
      port.postMessage({question: "Madame who?"});
    else if (msg.answer == "Madame... Bovary")
      port.postMessage({question: "I don't get it."});
  });
});

这就是你如何从特定端口捕获你的消息:

chrome.runtime.onConnect.addListener(function(port) {
  port.onMessage.addListener(function(msg) {
    console.log(msg) // msg object will be your message
  })
})