Chrome 扩展 - 未找到任何 DOM 元素

问题描述 投票:0回答:1

对于这个 Chrome 扩展,我尝试检索的任何 DOM 元素都返回为 null。我尝试了几个不同的网站,并尝试通过 ID、类和名称检索 DOM 元素。以下是 wikipedia.org 上的最新尝试

manifest.json

{
    "manifest_version": 3,
    "name": "Test",
    "version": "1.0",
    "description": "testing",
    "content_scripts": [
        {
            "run_at": "document_end",
            "js": ["scripts/content.js"],
            "matches": [
                "*://*.wikipedia.org/*",
                "*://wikipedia.com/*"
            ]
        }
    ],
    "action": {
        "default_popup": "hello.html"
    }
}

你好.html

<html>
  <body>
    <h1>Hello Extensions</h1>
    <script src="./scripts/content.js"></script>
  </body>
</html>

内容.js

document.addEventListener('DOMContentLoaded', function() {
  const domElem = document.getElementById('www-wikipedia-org')
  console.log(domElem);
});

window.onload = function() {
  const domElem = document.getElementById('www-wikipedia-org')
  console.log(domElem);
}
javascript html dom google-chrome-extension
1个回答
0
投票

如果我进行以下任一更改,Chrome 扩展程序将适用于我:

  1. 将清单更改为
    run_at: document_start

  1. 使用
    run_at: document_end
    但没有 DOMContentLoaded 甚至处理程序。

在这两种情况下,内容脚本都会找到 dom 元素。

换句话说,您不想将 DOMContentLoaded 与 document_end 一起使用。 当内容脚本运行时文档已经加载并且事件处理程序从未被触发。

© www.soinside.com 2019 - 2024. All rights reserved.