Lachezar Raychev
Lachezar Raychev

Reputation: 2113

Get content of an iframe after it loads with

I want to achieve the fallowing goal.I want by the click of a button to get the domain name entered in one input and load it into an iframe. What i have trouble with is after i load the specific site in the iframe how can i get the DOM of the loaded site in the iframe ? I need to save the exact path of an element of my choosing from the newly loaded site in the iframe by clicking on it. Any help would be much appreciated. Thank you.

Upvotes: 0

Views: 184

Answers (2)

pete
pete

Reputation: 25081

You can access the <iframe>'s contents via the contentDocument property.

var iFrameContent = $('myIFrame')[0].contentDocument;
$(iFrameContent).find('.mySelector').text();

I should also point out accessing the <iframe>'s contents can only be done if the src of the <iframe> is from the same domain as your script. If the src of the <iframe> is from any other domain, the browser will deny access to the <iframe>contents.

This is a CORS consideration.

UPDATE:

To get around the CORS limitation, you'll have to write a server-side proxy for the URL that is the src of the <iframe> (and it could be pretty simple).

If I were to do something like this in ASP.Net (as an example), I would write a web service that:

  1. takes the actual URL as a String parameter.
  2. Uses the HTTPWebRequest object (or similar) to get the URL contents.
  3. Return it back to the browser.

Then you could set your <iframe> src to "http://mysite.com/getURLService?url=www.lalala.com" and get the contents because the contents are now delivered by "http://mysite.com".

Upvotes: 1

Liam Bailey
Liam Bailey

Reputation: 5905

You use .contents()

like $("iframe").contents().find(); etc

Upvotes: 0

Related Questions