【问题标题】:How to send the message from popup.html to content script?如何将消息从 popup.html 发送到内容脚本?
【发布时间】:2018-03-27 20:20:38
【问题描述】:

我正在制作扩展程序,并希望将消息从 popup.html 传递到 content.js 但以下代码警告 undefined .请给我一个简单的脚本,将消息从 popup.html 发送到 content.js,反之亦然,我会进一步处理它。我想通过这个扩展访问 DOM 来修改和设计网站布局。

清单

{
  "manifest_version": 2,
  "name": "Extension",
  "description": "Description",
  "version": "1.0",
  "background": {
   "scripts": ["background.js"],
   "persistent": true
  },
  "content_scripts": [{
    "matches": ["*"],
    "js": ["content.js"]
  }],
  "browser_action": {
   "default_icon": "icons/icon.png",
   "default_popup": "popup.html"
  },
  "permissions":["tabs"]
}

popup.js

document.addEventListener('DOMContentLoaded',function(){

document.getElementById('button').onclick=function(){

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
            alert(response);
        });
    });

}

});

Content.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"});
});

【问题讨论】:

  • 您的代码对我有用。您是否在chrome://extensions/ 重新加载了您的扩展程序?
  • 它在警报中返回什么?
  • 它提醒对象,alert(response.farewell); 提醒再见。
  • 相信我这里不工作
  • 请在答案中输入相同的代码

标签: javascript google-chrome-extension


【解决方案1】:

试试这个简单的代码。

manifest.json

{
  "name": "test",
  "version": "0.1",
  "manifest_version": 2,

  "description": "Test Extension",

  "permissions": [ "tabs" ],

  "browser_action": {
    "default_popup": "popup.html"
  },
  "content_scripts" : [{
        "matches" :  ["*://*/*"],
        "js" : ["content.js"]
    }]
}

popup.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8" />
</head>
<body>
  <div id="data"></div>
  <input type="text" id="text"></input>
  <button id="set">Set</button>
  <script src="popup.js"></script>
</body>
</html>



> 

popup.js

document.getElementById("set").onclick = function() {

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
            alert(response.farewell);
        });
    });
}

content.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"});
});

提醒

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-07-03
  • 2013-11-29
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2020-10-12
相关资源
最近更新 更多