Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Chrome Extension - Accessing The DOM

I have been searching around the web to find out how to access the current tabs DOM to extract information out of a page from the background.html. So far I have had no luck, or at least nothing I could get to work properly.

To state the problem simply. I would like to get src of a iFrame on the page. Any Suggestions?

like image 801
mikemcmullan Avatar asked Jan 14 '10 08:01

mikemcmullan


People also ask

How do you inspect a DOM?

# Inspect a node When you're interested in a particular DOM node, Inspect is a fast way to open DevTools and investigate that node. Right-click Michelangelo below and select Inspect. The Elements panel of DevTools opens. <li>Michelangelo</li> is highlighted in the DOM Tree.

How can I see the DOM tree?

To do so, open the web page elk. html, turn on the browser developer tools and switch to the Elements tab. It should look like this: You can see the DOM, click on elements, see their details and so on.

What is DOM access?

The DOM defines a standard for accessing documents: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."


1 Answers

One way, you an treat this as a single one time request to the content-script which will fetch the dom you want to access. http://code.google.com/chrome/extensions/messaging.html#simple

Basically, your content script sets up the listener:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
    else
      sendResponse({}); // snub them.
  });

And your background page sends a single lived request:

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

When you send your response, you send it as JSON data, you can fetch whatever you want (such as html, dom, text, etc).

That is currently the only way to let the background page know anything about the contents of a page. Remember you would need content scripts and tab permissions.

like image 143
Mohamed Mansour Avatar answered Oct 18 '22 15:10

Mohamed Mansour