0

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?

Michael Tsai
  • 296
  • 1
  • 4
  • 11
  • 1
    `content_scripts` runs the scripts only when the tab was [re]loaded so I guess you didn't reload it after updating the extension on chrome://extensions page. Note that in this case it's better to switch to [programmatic injection](https://stackoverflow.com/a/4532567) via chrome.tabs.executeScript instead of `content_scripts`. – wOxxOm Jan 08 '21 at 17:11
  • Yes, you are right. The tab needs to be reload. Finally, it works now. thanks so much. – Michael Tsai Jan 08 '21 at 17:15

0 Answers0