jQuery - Parse iframe inserted after page loading

advertisements

I'm new to jQuery and having some trouble. A have a page that has a iframe inserted after the page loads. I need to find the anchor links in the content of the iframe and compare their href to a URL. Just trying the pure JavaScript getElementById() doesn't work because the iframe is inserted after the load. I read that I should be using either jQuery's live(), delegate(), or on(), but I'm not sure how they work. Also, if there is a pure Javascript solution that would be awesome as well.

The iframe I need to parse is:

<iframe src="http://assets.tumblr.com/iframe.html?10&src=http%3A%2F%2Fstaff.tumblr.com%2F&amp;lang=en_US&amp;name=staff"
    scrolling="no" width="330" height="25" frameborder="0"
    style="position:absolute; z-index:1337; top:0px; right:0px;
           border:0px; background-color:transparent; overflow:hidden;"
           id="tumblr_controls">
</iframe>

It is appended to every Tumblr blog (see Tumblr Staff Blog).

The part of the iframe's content I'm interested in looks like:

<div style="position:absolute; top:3px; right:3px; white-space:nowrap; height:20px;">
    <form action="/follow" method="post" style="display:block; float:left;" onsubmit="_gaq.push(['_trackEvent', 'Iframe', 'Follow', 'staff');">
    <input type="hidden" name="form_key" value="8W0r1XnbOEtpTF0q8oe96BmGMJg"/>
    <input type="hidden" name="id" value="staff"/>
    <input type="image" src="http://assets.tumblr.com/images/iframe_follow_alpha.png 1018" style="width:58px; height:20px; border-width:0px; display:block; margin-left:3px; cursor:pointer;" alt="Follow"/>
    </form>
    <a target="_top" href="http://www.tumblr.com/dashboard">
    <img src="http://assets.tumblr.com/images/iframe_dashboard_alpha.png?1018" alt="Dashboard" style="height:20px; width:81px; border-width:0px; display:block; float:left; cursor:pointer;"/>
</a>

I need to compare all the possible anchor links in this content and compare their hrefs to a URL.


function getHref() {

  var src = false,
      iframe = $('iframe#tumblr_controls');  // keep reference of iframe;
  // check that iframe loaded
  if( iframe.length) {
     src = iframe.find('a[target=_top]').attr('href');
  }
}

Now you can call getHref() to get the href of link within iframe and use that for comparison.

You can also try like following:

$('iframe#tumblr_controls').load(function() {
   var href = $(this).find('a[target=_top]').attr('href');
});

If you have multiple a tags within your content then try:

function compareHrefs() {
  var iframe = $('iframe#tumblr_controls');  // keep reference of iframe;
  // check that iframe loaded
  if( iframe.length) {
     // looping over each  tag
     iframe.find('a').each(function() {
          if ( this.href == TARGET_URL ) {
             // do something
          }
     });
  }
}