Accessing Current Tab DOM Object from "popup.html"?

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?


Solution 1:

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

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.

Solution 2:

This is the latest fix:

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

(Note: the above console.log(response.farewell) is for popup.html, not your current tab)

contentscript.js

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

Source: https://developer.chrome.com/extensions/messaging

Solution 3:

This answer seems to not be working with the latest API. This is a working example.

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

relevant parts of manifest.json:

{
  "permissions": [
      "tabs"
  ],

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