Chrome extension can't read activePage

Viewed 23

I have never made a chrome extension before but I am trying to make one and keep getting errors and am having trouble with the difference between manifest v2 and v3. The main thing I need this extension to be able to do is access the DOM of the active page, find a specific element's innerText by class, and then send the data back to the popup.html page to be displayed to the user. I am very new to javascript so any help on solving my problem would be amazing!

content_script.js

function getInfo() {
  try {
      var address = document.getElementsByClassName("classNameHere")[0].innerText;
      chrome.runtime.sendMessage({address: address});
   }
   catch(err) {
     console.log(`No info found`);
    }
}

getInfo();

popup.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello world</title>
  </head>
  <body>
    <h1>Test</h1>
    <p id="helloworld"></p>
  </body>
</html>

<script>
chrome.runtime.onMessage.addListener(
  function(address, sender, sendResponse) {
    document.getElementById("helloworld").innerHTML = address;
  }
);
</script>

manifest.json

{
    "name": "Hello World",
    "version": "0.1.0",
    "manifest_version": 3,
    "content_scripts": [{
            "matches": ["https://google.com/*"],
            "js": ["content_script.js"]    
    }],
    "action": {
      "default_title": "Test extension"
    }
}
1 Answers

your code is mostly fine, but it only works while you keeping the popup open and refresh the page. (mostly it won't work because once you focus on your tab content, your popup will close).

So this will be a bit tricky. but you can try this way:

  • when you open the popup, send a message to content script, tell it to get the content you want
  • content script get message and get content then send back to popup
  • popup shows the message

so you will need to add a message sending function to your popup and message listener to you content script. like this:

  • popup.html, you should always put everything inside <html> tag
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello world</title>
  </head>
  <body>
    <h1>Test</h1>
    <p id="helloworld"></p>
<script>
// sends message
chrome.runtime.sendMessage({action: 'getInfo'})
chrome.runtime.onMessage.addListener(
   function(address, sender, sendResponse) {
     document.getElementById("helloworld").innerHTML = address;
   }
);
</script>
  </body>

</html>
  • content script

function getInfo() {
  try {
      var address = document.getElementsByClassName("classNameHere")[0].innerText;
      chrome.runtime.sendMessage({address: address});
   }
   catch(err) {
     console.log(`No info found`);
    }
}

chrome.runtime.onMessage.addListener((req, sender, sendResponse)->{
if(req.action === 'getInfo'){
    getInfo();
})

Related