I'm working on a pretty simple browser extension, but can't get the message passing to work: I can send messages, but the response is never delivered!

My code: Its mostly just a copy from the browserActions tutorial, contentscripts tutorial (manifest) and message-passing api definition.

manifest.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://*/*"]
  }],
}

background.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>
有帮助吗?

解决方案

Since the message from your popup to the content script is sent whenever the popup is loaded, be sure to reload the page to ensure the content script is loaded. Otherwise, you could end up with the following error:

Could not establish connection. Receiving end does not exist.

That said, I tried what you provided, and it worked as is. Since your output is in popup.js, the response is in the console output of the popup. You can view it by right-clicking on your browser action icon, and selecting 'Inspect popup'.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top