简体   繁体   English

chrome扩展消息没有响应

[英]chrome extension message passing no response

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. 我的代码:它基本上只是浏览器操作指南,内容脚本指南(清单)和消息传递api定义的副本。

manifest.json: 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 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 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 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. 由于您的输出在popup.js中,因此响应在弹出窗口的控制台输出中。 You can view it by right-clicking on your browser action icon, and selecting 'Inspect popup'. 您可以通过右键单击浏览器操作图标,然后选择“检查弹出窗口”来查看它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM