如何将邮件从popup.html发送到内容脚本?

时间:2018-03-27 10:53:17

标签: javascript google-chrome-extension

我正在进行扩展,并希望将消息从 popup.html 传递到 content.js ,但以下代码提醒未定义 。请给我一个简单的脚本,将 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"});
});

1 个答案:

答案 0 :(得分: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"});
});
  

警报

enter image description here