如何在Chrome扩展程序弹出窗口和内容脚本之间发送消息?

时间:2016-03-22 12:07:18

标签: javascript google-chrome

在Google教程之后,我将从弹出脚本向内容脚本发送消息。消息正确传递但是当我调用响应回调时,我收到以下错误:

Attempting to use a disconnected port object

这是popup.js:

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

这是content.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    sendResponse('goodbye'); // <- Error here
  });

如何发送此消息并获得回复?

2 个答案:

答案 0 :(得分:0)

原来这是由于内容页面上的警报导致弹出窗口关闭。这反过来又打破了弹出窗口和内容脚本之间的连接。

答案 1 :(得分:-1)

此示例演示如何向所选选项卡中的内容脚本发送消息。

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

参考Link