javascript - Chrome扩展端口错误: Could not establish connection.接收端不存在

标签 javascript google-chrome-extension

尝试从弹出窗口向我的 contentscript 发送消息时出现此错误。我想要做的是从我的 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.接收端不存在。杂项绑定(bind):235 chromeHidden.Port.dispatchOnDisconnect

修复了 list 中“persistent”的拼写错误
更新了 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));
    });
  });

最佳答案

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

Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.

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

此外,您在 list 文件中拼错了“persistent”。我不希望您在发现导致问题的原因之前不得不花半个小时深入研究代码。

关于javascript - Chrome扩展端口错误: Could not establish connection.接收端不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17266737/

相关文章:

javascript - 如何让div在特定高度后淡入?

jquery - Google Chrome 扩展程序 - 需要帮助

javascript - chrome.notifications 消息未显示

javascript - 我的 javascript for-in 循环出了什么问题

javascript - Meteor:WAITING库准备好

javascript - 如何获取iframe元素?

javascript - Screeps-如何使路径计算一致?

javascript - YouTube 播放器 API : retrieving a reference to an existing player

php - 如何通过 chrome 扩展存储用户特定的数据

javascript - 使用谷歌翻译开发谷歌浏览器扩展