对于这个 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);
}
如果我进行以下任一更改,Chrome 扩展程序将适用于我:
run_at: document_start
或
run_at: document_end
但没有 DOMContentLoaded 甚至处理程序。在这两种情况下,内容脚本都会找到 dom 元素。
换句话说,您不想将 DOMContentLoaded 与 document_end 一起使用。 当内容脚本运行时文档已经加载并且事件处理程序从未被触发。