从“popup.html"访问当前选项卡DOM对象? [英] Accessing Current Tab DOM Object from "popup.html"?
问题描述
我正在为 Google Chrome 浏览器开发一个扩展程序.我无法弄清楚如何从popup.html"页面访问当前选项卡 DOM 对象.有什么建议吗?
I'm developing an extension for Google Chrome browser. I could not figure out how to access the current tab DOM object from the "popup.html" page. any suggestions?
推荐答案
默认情况下,在 popup.js/popup.html 中,文档"对象仅指扩展的弹出窗口的文档.要获取特定选项卡(例如当前活动选项卡)的 DOM,您需要使用 内容脚本通信.例如,我们需要从 extension 向您的通过 popup 编写内容脚本,因此在 popup.html 中您可以执行以下操作:
By default, within popup.js/popup.html, the "document" object refers to the extension's popup window's document only. To get the DOM for a specific tab (for instance the currently active tab), you would need to use content scripts communications. For example we need to send a request from the extension to your content script via popup, so in the popup.html you do something like this:
chrome.tabs.getSelected(null, function(tab) {
// Send a request to the content script.
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
console.log(response.dom);
});
});
现在在内容脚本中,我们需要监听这些事件 来自扩展名,所以在一些文件中我们命名为 dom.js
Now in the content script, we need to listen for those events coming from the extension, so in some file we named dom.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.action == "getDOM")
sendResponse({dom: "The dom that you want to get"});
else
sendResponse({}); // Send nothing..
});
现在记得设置您的 manifest 以包含内容脚本和选项卡权限.
Now remember to setup your manifest to include the content script and tab permission.
这篇关于从“popup.html"访问当前选项卡DOM对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!