我一直在寻找如何实现这一点。我发现了一些最值得注意的文章
Accessing Current Tab DOM Object from "popup.html"?
但是我对 JavaScript 和制作 chrome 扩展还很陌生,我已经走到了死胡同。
我的猜测是没有收到响应,这解释了为什么 document.write("Hellp")
不工作。任何解决此问题的帮助将不胜感激。
我有三个主要文件
list .json
{
"name": "My First Extension",
"version": "1.0",
"description": "The first extension that I made.",
"browser_action":
{
"default_icon": "icon.png",
"popup": "popup.html"
},
"permissions":
[
"tabs"
],
"content_scripts":
[{
"matches": ["<all_urls>"],
"js": ["dom.js"]
}]
}
弹出窗口
<html>
<body>
</body>
<script>
chrome.tabs.getSelected(null, function(tab)
{
// Send a request to the content script.
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response)
{
document.write("Hello");
document.write(response.title)
});
});
</script>
</html>
dom.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
{
if (request.action == "getDOM")
sendResponse({dom: document.getElementsByTagName("body")[0]});
else
sendResponse({}); // Send nothing..
});
最佳答案
我看到这是一个较旧的问题,但没有答案,我遇到了同样的问题。也许这是一项安全功能,但您似乎无法返回 DOM 对象。但是,您可以返回文本。所以对于 dom.js:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.action == "getDOM")
sendResponse({dom: document.body.innerHTML});
else
sendResponse({}); // Send nothing..
});
关于javascript - 从 Chrome 扩展访问当前选项卡 DOM 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4374793/