开发Chrome插件,在content.js中使用 document.getElementsByTagName获取页面的DOM,
然后遍历DOM的属性,却遍历不到自定义属性。
manifest.json文件:
{
"manifest_version": 2,
"name": "test",
"version": "1.0.0",
"background": {
"scripts": [
"background.js"
]
},
"icons": {
"16": "icons/webpack.16.png",
"48": "icons/webpack.48.png",
"128": "icons/webpack.128.png"
},
"browser_action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"content.js"
],
"css": [
"style.css"
]
}
]
}
popup.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8" />
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="btn">点击</button>
<script src="popup.js"></script>
</body>
</html>
popup.js文件:
document.getElementById('btn').addEventListener('click', function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: 'click'}, function (response) {
console.log('+++++', response)
})
})
},false)
content.js文件:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('-------chrome 插件 content.js中获取 document.getElementById("root")._reactRootContainer值', document.getElementById('root')._reactRootContainer);
if(request.type === 'click') {
console.log('收到来自popup的消息');
}
sendResponse('我是content-script,已收到你的消息');
})
style.css文件:
button {
color: white;
background: black;
}
background.js文件:
console.log('background')
使用 create-react-app 创建一个项目,打开浏览器使用插件,运行效果如图:
在插件的 content.js 中 使用 document.getElementById("root")._reactRootContainer 取值得 undefined;
在浏览器的 Console 面板中可以获取到值。
请问原因是什么? 怎么解决?
设置一下定时器,延迟2s获取看看