문제

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
  }
}
도움이 되었습니까?

해결책

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.

다른 팁

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",
  ]
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top