我正在尝试从网页访问一些 DOM 元素:
<html>
<button id="mybutton">click me</button>
</html>
我想通过 chrome 扩展访问 innerHTML(“点击我”):
chrome.browserAction.onClicked.addListener(function(tab) {
var button = document.getElementById("mybutton");
if(button == null){
alert("null!");
}
else{
alert("found!");
}
});
当我点击扩展时,弹出窗口显示:“null”。 我的 manifest.json:
{
"name": "HackExtension",
"description": "Hack all the things",
"version": "2.0",
"permissions": [
"tabs", "http://*/*"
],
"background": {
"scripts": ["contentscript.js"],
"persistent": false
},
"browser_action": {
"scripts": ["contentscript.js"],
"persistent": false
},
"manifest_version": 2
}
最佳答案
解决方法: 您需要一个 list 文件、一个后台脚本和一个内容脚本。在您必须使用它以及如何使用它的文档中,这并不是很清楚。要提醒整个 dom,请参阅 here .因为我很难找到一个真正有效的完整解决方案,而不仅仅是对像我这样的新手无用的片段,所以我提供了一个特定的解决方案:
list .json
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["file:///*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
content.js
/* Listen for messages */
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
/* If the received message has the expected format... */
if (msg.text && (msg.text == "report_back")) {
/* Call the specified callback, passing
the web-pages DOM content as argument */
sendResponse(document.getElementById("mybutton").innerHTML);
}
});
background.js
/* Regex-pattern to check URLs against.
It matches URLs like: http[s]://[...]stackoverflow.com[...] */
var urlRegex = /^file:\/\/\/:?/;
/* A function creator for callbacks */
function doStuffWithDOM(element) {
alert("I received the following DOM content:\n" + element);
}
/* When the browser-action button is clicked... */
chrome.browserAction.onClicked.addListener(function(tab) {
/*...check the URL of the active tab against our pattern and... */
if (urlRegex.test(tab.url)) {
/* ...if it matches, send a message specifying a callback too */
chrome.tabs.sendMessage(tab.id, { text: "report_back" },
doStuffWithDOM);
}
});
index.html
<html>
<button id="mybutton">click me</button>
</html>
只需将 index.html 保存在某处并作为扩展名加载到文件夹中,其中包含其他三个文件。打开 index.html 并按下扩展按钮。它应该显示“点击我”。
关于javascript - 通过 chrome 扩展访问 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21314897/