document.querySelector始终返回null [英] document.querySelector always returns null
问题描述
我看了其他答案,但还是不明白.
I've looked at the other answers but still don't understand.
出于某种原因,此行代码始终返回null.
For some reason this line of code always returns null.
var els = document.querySelector("[id='MTG_INSTR$2']");
我在控制台中检查了文档的值,所以我很确定这是正确的.
I checked the value of document in the console so I'm pretty sure that's correct.
该ID会被深深地埋在桌子内,这可能是个问题吗?
The id is buried deep inside a table though, could that be an issue?
如果有帮助,这是完整的代码.
EDIT 2: If it helps, here's the full code.
content.js
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
start();
}
}
);
function start(){
var els = document.querySelector("[id='MTG_INSTR$2']");
console.log(els);
alert("started");
}
popup.html
popup.html
<!DOCTYPE html>
<html>
<head></head>
<script src="popup.js"></script>
<body>
<input id="button1" type=button value=clickme>
</body></html>
popup.js
function popup() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
});
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("button1").addEventListener("click", popup);
});
manifest.json
manifest.json
{
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"manifest_version": 2,
"name": "extensiontest",
"version": "0.2",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup":"popup.html"
},
//"background": {
// "scripts": ["background.js"]
//},
"permissions": [
"tabs"
]
}
我提供了文档结构的屏幕快照.
I've included a screen shot of what the document structure looks like.
推荐答案
我怀疑您的JS是否在标记和CSS之前加载.在这种情况下,您可以尝试使用< script src =" defer></script>
I doubt your JS gets loaded before the markup and css. In that case, you could try using
<script src="" defer></script>
首先加载内容,然后您的Java脚本应该可以正常工作.
The contents are loaded first and your java script should work fine after that.
这篇关于document.querySelector始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!