0

我正在开发一个非常简单的浏览器扩展程序,但无法让消息传递工作:我可以发送消息,但永远不会传递响应!

我的代码:它主要是 browserActions 教程、contentscripts 教程(清单)和消息传递 api 定义的副本。

清单.json:

{
    "manifest_version":2,
  "name": "FUN SCRIPT",
  "version": "1",
  "description": "THIS IS SOME FUN SCRIPT",
  "browser_action": {
    "name": "Fun",
    "icons": ["icon.png"],
    "default_icon": "icon.png",
     "default_popup": "popup.html"
  },
  "content_scripts": [ {
    "js": [ "jquery.js", "background.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }],
}

背景.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

popup.js

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

popup.html

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        min-width: 357px;
        overflow-x: hidden;
      }

      img {
        margin: 5px;
        border: 2px solid black;
        vertical-align: middle;
        width: 75px;
        height: 75px;
      }
    </style>
    <script src="popup.js"></script>
  </head>
  <body>
  </body>
</html>
4

1 回答 1

0

由于每当加载弹出窗口时都会发送从弹出窗口到内容脚本的消息,因此请务必重新加载页面以确保加载内容脚本。否则,您可能会遇到以下错误:

Could not establish connection. Receiving end does not exist.

也就是说,我尝试了您提供的内容,并且按原样工作。由于您的输出位于 popup.js 中,因此响应位于弹出窗口的控制台输出中。您可以通过右键单击浏览器操作图标并选择“检查弹出窗口”来查看它。

于 2013-10-14T11:48:49.303 回答