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

时间:2017-07-19 00:31:18

标签: 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;
        }
    }
);

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>

2 个答案:

答案 0 :(得分:8)

chrome.tabs.getCurrent 用于:

  

获取此脚本调用的选项卡

您的 popup.js 应为:

var values = "160,159,158,157,156,155,143,141,140,139";
var final  = values .split(',').reduce(function(accumulator, currentValue, 
 currentIndex) {
      accumulator[currentValue] = currentIndex;
       return accumulator;
},{});

答案 1 :(得分:3)

要添加到上面的答案,您经常需要从弹出窗口向所有标签发送消息,所以

弹出:

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

内容脚本:

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