Question

For some reason, when I try to use getElementsByTagName in my Chrome Extension, I get an empty list. For example:

background.js

document.body.onload = function(){
    chrome.browserAction.onClicked.addListener(function(tab) {
        alert(document.getElementsByTagName("div").length);
    });
};

will alert me "0". In addition, if inside my addListener function I create a div and append it to the body, the length becomes "1". So it seems like the extension only detects objects created after the extension was clicked...any ideas?

P.S. here is my manifest file

manifest.json

{
  "name": "tester",
  "version": "1.0",
  "manifest_version": 2,
  "background": {
      "scripts": ["background.js"],
      "persistent": false
  }
}
Was it helpful?

Solution

The background.js script is executed inside the background page context. Here, since you only declare a background script, your background page is generated, and doesn't have any content.

You can see the generated background page by going to chrome://extensions/ and clicking on the Inspect views: _generated_background_page.html link next to your extension. It will look like this:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script src="background.js"></script>
  </body>
</html>

As you can see, there are no <div> element, and therefore document.getElementsByTagName("div").length will return 0.

If you want to get the content of the web page, you'll have to use a content script.

OTHER TIPS

Just a follow-up, here is the code I used. It works by injecting a script into the active tab whenever the extension button is clicked (more info here)

injected.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {file: "testscript.js"});
});

testscript.js

document.body.style.backgroundColor="red";

manifest.json

{
  "name": "injecttester",
  "version": "1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_icon": "icon.png"
  },
  "background": {
      "scripts": ["injected.js"],
      "persistent": false
  },
  "permissions": [
  "activeTab",
  ]
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top