【问题标题】:Sending message from popup to content script - Chrome Extension将消息从弹出窗口发送到内容脚本 - Chrome 扩展
【发布时间】:2017-12-24 01:13:32
【问题描述】:

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

内容.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_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

<!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>

【问题讨论】:

  • tabs.getCurrent 不是你想象的那样。使用 tabs.query。在第一次使用方法之前,请务必检查 API 文档。另请注意,重新加载扩展程序时不会自动注入内容脚本。

标签: google-chrome-extension


【解决方案1】:

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

弹出:

chrome.tabs.query({}, tabs => {
    tabs.forEach(tab => {
    chrome.tabs.sendMessage(tab.id, msgObj);
  });
});

内容脚本:

chrome.runtime.onMessage.addListener(msgObj => {
    // do something with msgObj
});

【讨论】:

    【解决方案2】:

    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);
        });
    });
    

    【讨论】:

    • 你需要它是chrome.tabs.query({active:true,currentWindow:true}...。您需要指定currentWindow:true 才能将结果限制在当前窗口中。如果您不这样做,那么当用户打开多个窗口时,您将遇到间歇性问题(即,有时tabs[0] 将是当前窗口中的活动选项卡,有时它将是其他窗口中的活动选项卡)。
    • @Deliaz 如何将消息/数据从 content.js 发送到 popup.js ?请帮助
    • @DeanVanGreunen,检查这个问题How to send data from content script to popup.html
    猜你喜欢
    • 2013-10-12
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    相关资源
    最近更新 更多