views:

590

answers:

1

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?

+1  A: 

Hello,

To get the DOM from a specific 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.

Mohamed Mansour
I mean with the DOM is Document Object Model ... thanks
Khaled Musaied
Yes, what I showed you in my example is synchronous messaging done in Chrome Extensions. I returned a String "The dom that you want to get", but in reality, you can return any DOM you want. If you want to get everything in body you can do "sendResponse({dom: document.getElementsByTagName("body")[0]});"
Mohamed Mansour