Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

javascript - chrome.runtime.onmessage.addlistener cannot receive the message

I want to make a chrome extension to remove the element in the website. However, I found that the message cannot be passed from popup.js to contentScript.js

manifest.json

{
"manifest_version": 2,
"name": "Remove Element",
"description": "Remove Element in websites.",
"version": "1.0.0",
"icons": {
  "128": "icon.png"
},
"browser_action": {
  "default_icon": "icon.png",
  "default_popup": "popup.html"
},
"permissions": [
  "activeTab",
  "tabs"
],
"content_scripts" : [ { 
  "matches" : [ "https://*/*", "http://localhost/*"],
  "js" : [ "contentScript.js" ]
} ]
}

popup.js

delthis = () => {

    chrome.tabs.query({ active: true, currentWindow: true },    
        function(tabs) {       
          chrome.tabs.sendMessage(tabs[0].id, {elemt: document.getElementById("getelem").value});
          
        }
      );
}


document.getElementById("del").addEventListener("click", delthis);

contentScript.js

onMessage = (msg, sender, senders) => {
    document.getElementById(msg.elemt).remove();
}

chrome.runtime.onMessage.addListener(onMessage);

popup.html

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" style="width:100px;">
  <head>
    <title>Remover</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body id="body">
    <input type="text" id="getelem" size="5"></input>
    <button id="del">Delete</button>
    <script src="popup.js"></script>
  </body>
</html>

Here is my code. I send the message from the popup.js to the active tab but the contentScript.js cannot receive the message. How can I solve this problem?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...