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

use*_*676 11 google-chrome-extension

我想通过浏览器操作按钮打开它时更新popup.html中的html.popup.js应该向当前选项卡上运行的内容脚本发送消息,并且应该收到响应并更新html.但是,内容脚本不会收到任何消息,因此不会发送正确的响应.

Content.js

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

Popup.js

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

的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"]
  }]
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Del*_*iaz 11

chrome.tabs.getCurrent用于:

获取此脚本调用的选项卡

你的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);
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 您需要将其设置为 `chrome.tabs.query({active:true,currentWindow:true}...`。您需要指定 `currentWindow:true` 以便将结果仅限于当前窗口。如果您不这样做t,那么当用户打开多个窗口时,您将遇到间歇性问题(即有时“tabs[0]”将是当前窗口中的活动选项卡,有时它将是其他窗口中的活动选项卡)。 (3认同)
  • @DeanVanGreunen,检查这个问题[How to send data from content script to popup.html](/sf/ask/1401397091/ to-popup-html) (2认同)

kof*_*fus 8

要添加到上述答案,您通常希望从弹出窗口向所有选项卡发送消息,因此

弹出:

chrome.tabs.query({}, tabs => {
    tabs.forEach(tab => {
    chrome.tabs.sendMessage(tab.id, msgObj);
  });
});
Run Code Online (Sandbox Code Playgroud)

内容脚本:

chrome.runtime.onMessage.addListener(msgObj => {
    // do something with msgObj
});
Run Code Online (Sandbox Code Playgroud)