问题:我正在尝试创建一个简单的 Chrome 扩展程序来帮助我的工作,而且我的函数似乎在创建 DOM 之前尝试在 DOM 中查找该对象。
错误信息
我尝试过的:
window.onload = function () {}
中document.addEventListener('DOMContentLoaded', function () {}
中<script></script>
标签移动到我的 popup.html 文档的底部。chrome.browserAction.onClicked
方法,虽然我可能没有正确使用它,因为我对它们很陌生。代码库现在所处的位置
manifest.json 文件:
{
"short_name": "Shadow",
"name": "Shadow Root Finder",
"version": "1.0",
"description": "highlights elements where shadowRoots are present",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["contents.js"]
}
],
"permissions": [
"storage",
"activeTab",
"declarativeContent"
],
"icons": {
"192": "/images/192_192_mission.png",
"512": "/images/512_512_mission.png"
},
"background": {
"scripts": [
"background.js",
"contents.js"
],
"persistent": false
},
"browser_action" : {
"default_popup" : "popup.html",
"default_icon" : {
"48": "/images/192_192_mission.png",
"128": "/images/512_512_mission.png"
}
},
"manifest_version": 2
}
popup.html 文件:
<html>
<head>
<style>
button {
height: 20px;
width: 20px;
}
</style>
</head>
<body>
<button id="searchTheShadowsButton"></button>
</body>
</html>
background.js 文件:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
code: "/contents.js",
allFrames: true
});
});
content.js 文件:
document.addEventListener('DOMContentLoaded', function() {
//define variables
let blue = '#5F9CE0';
let peach = '#E07255';
let red = '#AD395A';
let count = 0;
let nodeList = [];
let windowDoc = document.getElementsByTagName('*');
//define function
function beginSearch () {
console.log('search the Shadows activated: line 10')
for (i = 0; i < windowDoc.length; i++) {
console.log("entered for loop")
if (windowDoc[i].shadowRoot) {
console.log("entered if statement")
count +=1;
console.log('current count is: ' + count);
windowDoc[i].parentNode.style.background = blue;
nodeList.push(windowDoc[i].host.nodeName);
console.log('nodes with shadowRoots include: ' + nodeList)
}
}
};
//set up listener
document.getElementById('searchTheShadowsButton').addEventListener('click', beginSearch)
})
预期的用户界面: