从“popup.html”访问当前选项卡DOM对象?

时间:2009-12-26 20:02:33

标签: javascript google-chrome

我正在为Google Chrome浏览器开发扩展程序。 我无法弄清楚如何从“popup.html”页面访问当前标签DOM对象。 有什么建议吗?

3 个答案:

答案 0 :(得分:25)

默认情况下,在popup.js / popup.html中,“document”对象仅引用扩展程序的弹出窗口文档。要获取特定选项卡的DOM(例如当前活动的选项卡),您需要使用content scripts communications。例如,我们需要通过extensionpopup的请求发送到您的内容脚本,因此在popup.html中您可以执行以下操作:

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);
  });
});

现在在内容脚本中,我们需要listen for those events来自扩展,所以在某个文件中我们命名为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以包含内容脚本和标签权限。

答案 1 :(得分:3)

这个答案似乎不适用于最新的API。这是一个有效的例子。

popup.js:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];
    console.log(tab.url, tab.title);
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(msg) {
            msg = msg || {};
            console.log('onResponse', msg.farewell);
        });
    });
});

getDescription.js:

window.onload = function() {
    chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
        console.log('onMessage', msg);
        if (msg.greeting == "hello") {
            sendResponse({farewell: "goodbye"});
        } else{
           sendResponse({});
        }
    });
};

manifest.json的相关部分:

{
  "permissions": [
      "tabs"
  ],

  "content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
        "js": ["getDescription.js"]
    }
   ]
}

答案 2 :(得分:2)

这是最新修补程序:

popup.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
      console.log(response.farewell);
  });
});

(注意:上面的console.log(response.farewell)是针对popup.html的,而不是你当前的标签)

contentscript.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

来源:https://developer.chrome.com/extensions/messaging