提问人:Jezor 提问时间:9/1/2023 更新时间:9/1/2023 访问量:127
如何在 Chrome 扩展程序清单 V3 内容脚本中访问/修改 DOM 元素?
How to access / modify DOM elements in Chrome Extension Manifest V3 content script?
问:
我有一个简单的 Chrome 扩展程序,可以在控制台中记录元素的 ID,并将所有文本元素类更改为“test”。
我:manifest.json
{
"manifest_version": 3,
"name": "Access DOM Example",
"description": "A script accessing and modifying DOM elements",
"version": "1.0",
"content_scripts": [{
"matches": ["<all_urls>"],
"css": ["test.css"],
"js": ["test.js"],
"match_about_blank": false,
"run_at": "document_end",
"world": "MAIN"
}]
}
和内容脚本, :test.js
walk(document.body);
function walk(node) {
let child, next;
switch (node.nodeType) {
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while (child) {
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // Text node
console.log(node.id); // shows 'undefined'
node.className = "test"; // change is never applied, why?
break;
}
}
然而,对于一个简单的页面:
<html lang="en">
<body>
<div id="hello-world">Hello, World!</div>
</body>
</html>
脚本在控制台中显示“undefined”,并且不应用对类名的更改。
有什么方法可以从内容脚本修改 DOM?
答: 暂无答案
评论
id
className
"world": "MAIN"