Chrome扩展程序端口错误:无法建立连接。接收端不存在

时间:2013-06-24 00:53:42

标签: javascript google-chrome-extension

尝试从弹出窗口向我的脚本发送消息时出现此错误。我想要做的是从我的content.js获取当前选项卡的文档并将其发送到弹出窗口。我该如何修复这个错误?

{
  "manifest_version": 2,
  "name": "Chrome Snapshot",
  "description": "Save images and screenshots of sites to Dropbox.",
  "version": "1.0",
  "permissions": [
    "<all_urls>",
    "tabs"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "html/popup.html"
  },
  "background": {
    "scripts": [
      "vendor/dropbox.min.js",
      "vendor/jquery-2.0.2.min.js"
    ],
    "persistant": false
  },
  "content_scripts" : [{
    "all_frames": true,
    "matches" : ["*://*/*"],
    "js" : ["js/content.js"],
    "run_at": "document_end"
  }]
}

JS / popup.js

chrome.runtime.sendMessage({message: 'hi'}, function(response) {
  console.log(response);
});

JS / content.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  console.log('message', message);
  sendResponse({farewell: 'goodbye'}); 
});

编辑#1 仍然收到相同的错误Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:235 chromeHidden.Port.dispatchOnDisconnect

在清单中修复了错误拼写的“持久性” 更新了js / popup.js

chrome.tabs.query({'active': true,'currentWindow':true}, function(tab){
    console.log('from tab', tab[0]);
    chrome.tabs.sendMessage(tab[0].id, {message: 'hi'}, function(response){
      console.log(JSON.stringify(response));
    });
  });

1 个答案:

答案 0 :(得分:4)

您需要使用chrome.tabs.sendMessage向内容脚本发送消息。来自Chrome开发者网站上的chrome.runtime.sendMessage规范:

  

请注意,扩展程序无法使用此方法向内容脚本发送消息。要将消息发送到内容脚本,请使用tabs.sendMessage。

如果这不适合您,您可以让每个内容脚本打开一个到您的后台页面的端口(可能需要持久化),然后让您的弹出页面向您的后台页面发送消息,它会通过每个端口将消息中继到所有内容脚本,以告诉他们将消息发送回弹出页面。 (使用chrome.runtime.connect。)

此外,您在清单文件中拼错了“持久性”。我不希望你在发现造成问题之前必须深入挖掘代码半小时。