How to send the message from popup.html to content script?

和自甴很熟 提交于 2020-01-14 02:41:40

问题


I am making an extension and want to pass the message from the popup.html to content.js but the following code alert undefined. Please give me a simple script that send message from popup.html to content.js and vice versa, further i will handle it. I want to access the DOM through this extension for modifying and designing the website layouts.

Manifest

{
  "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:


Try this simple code.

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

alert



来源:https://stackoverflow.com/questions/49511012/how-to-send-the-message-from-popup-html-to-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!