将消息从弹出窗口发送到内容脚本-Chrome扩展程序

问题描述:

通过浏览器操作按钮打开popup.html中的html时,我想对其进行更新. popup.js应该向当前选项卡上运行的内容脚本发送一条消息,并应该收到响应并更新html.但是,内容脚本没有收到任何消息,因此没有发送适当的响应.

I want to update the html in popup.html when I open it through the browser action button. The popup.js should send a message to the content script running on the current tab, and should receive a response and update the html. However the content script does not receive any message, therefore not sending a proper response.

Content.js

Content.js

var text = "hello";
chrome.runtime.onMessage.addListener(
    function(message, sender, sendResponse) {
        switch(message.type) {
            case "getText":
                sendResponse(text);
            break;
        }
    }
);

Popup.js

chrome.tabs.getCurrent(function(tab){
    chrome.tabs.sendMessage(tab.id, {type:"getText"}, function(response){
        alert(response)
        $("#text").text(response);
    });
});

Manifest.json

Manifest.json

{
  "manifest_version": 2,
  "name": "It's Just A Name",
  "description": "This extension is able to",
  "version": "1.0",
  "permissions" : ["tabs"],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click here!"
  },
  "content_scripts": [
  {
    "matches": ["https://*/*"],
    "js": ["jquery.min.js","content.js"]
  }]
}

Popup.html

Popup.html

<!doctype html>
<html>
    <head>
        <title>Title</title>
        <style>
            body {
                font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
                font-size: 100%;
            }
            #status {
                white-space: pre;
                text-overflow: ellipsis;
                overflow: hidden;
                max-width: 400px;
            }
        </style>
        <script src="popup.js"></script>
    </head>
    <body>
        <p id="text"></p>
    </body>
</html>

chrome.tabs.getCurrent 用于:

获取进行此脚本调用的标签页

Gets the tab that this script call is being made from

您的 popup.js 应该是:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {type:"getText"}, function(response){
        alert(response)
        $("#text").text(response);
    });
});