从“popup.html”中访问当前选项卡DOM对象? [英] Accessing Current Tab DOM Object from "popup.html"?

查看:148
本文介绍了从“popup.html”中访问当前选项卡DOM对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发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(例如当前活动标签),您需要使用内容脚本通信。例如,我们需要将来自扩展程序的请求发送到您的内容脚本通过弹出,因此在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..
});

现在请记得设置您的清单,以包含内容脚本和标签权限。

Now remember to setup your manifest to include the content script and tab permission.

这篇关于从“popup.html”中访问当前选项卡DOM对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆