2

Example:

iframe.html

<a href="http://www.google.com">Google</a>
bla bla bla
<a href="http://www.yahoo.com">Yahoo</a>

index.html

<script>
...
</script>
There are the links from "iframe.html"
http://www.google.com
http://www.yahoo.com
hugo
  • 27
  • 2
  • 4
  • Is index.html and iframe.html in the same domain? – wong2 Jul 14 '11 at 05:21
  • Does `iframe.html` have the same domain, protocol and port as `index.html`? – alex Jul 14 '11 at 05:22
  • See this answer. [detect url's in text with Javascript](http://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript/1500501#1500501) – Adeel Jul 14 '11 at 05:22
  • @Adeel: That is detecting URLs in strings. The OP wants links in the DOM. – alex Jul 14 '11 at 05:31

2 Answers2

3

If the domain, protocol and ports match, just use...

var links = $('iframe:first').contents()[0].links;

jsFiddle.

...or without jQuery...

var iframe = document.getElementsByTagName('iframe')[0],
    doc = iframe.contentDocument || iframe.contentWindow.document; 

var links = doc.links;

jsFiddle.

This takes advantage of the document.links property.

alex
  • 479,566
  • 201
  • 878
  • 984
  • That's cool but he'd still have to iterate that array to display them, likely with `$.each()` so it doesn't really save him much effort over just iterating the anchors directly from the `contents()` selector, right? – AlienWebguy Jul 14 '11 at 06:59
  • @AlienWebGuy It returns more than `a` elements, and only `a` elements with a `href` attribute. – alex Jul 14 '11 at 07:40
1

Assuming your iframe is on the same domain as your website, and has the id "my_iframe" and you have a div with the id "results", this should work for you:

$("#my_iframe").contents().find('a').each({
    $('#results').append($(this).attr('href') + '<br />');
});

Take a moment to read up on JQuery's .contents() function.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145