【发布时间】:2017-10-12 08:26:15
【问题描述】:
我看过其他答案,但还是不明白。
由于某种原因,这行代码总是返回 null。
var els = document.querySelector("[id='MTG_INSTR$2']");
我在控制台中检查了文档的值,所以我很确定这是正确的。
id 隐藏在表格深处,这可能是个问题吗?
编辑 2:如果有帮助,这里是完整的代码。
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
<!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
{
"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"
]
}
编辑:我已经包含了文档结构的屏幕截图。
【问题讨论】:
-
如果你想选择具有定义id的元素,像这样使用它 document.querySelector("#MTG_INSTR$2")
标签: javascript