views:

169

answers:

2

Hi,

I am trying to intercept links clicked on a page including those inside an iframe. This is the code that I have but it is not working. Any ideas what I need to do?

$("#container").delegate('a', 'click', function(e){ 
//do stuff
}

Container is the id of the div just inside the iframe.

Thanks in advance for any advice

A: 

You need to reach inside the <iframe> and set the delegate there, you can do it like this:

$('#myiframe').contents().find("#container").delegate('a', 'click', function(e){ 
  //do stuff
}

Edit - Mailslut makes a good points below, if the iframe isn't on the same domain (and port), you can't do anything like this. If that's the case and you want to know more about why, read about the same-origin policy there for security reasons.

Nick Craver
Is the page within the IFRAME from a different domain? If so, you should really forget about being able to do this.
Mailslut
The page could be anything really. It is most likely to be another internal site so our site is our-site.blah.com and the links in the iframe are likely to be something-else.blah.com - will that work?
Kaskade
@Kaskade - You'd hit the same origin policy there, if you were running the main page from `blah.com` and the iframe was `something-else.blah.com` it would work, as it's a sub domain of the current domain, but a sibling will not...since say `google.com` is a sibling of `yourbank.com`, both subs of the `com` domain.
Nick Craver
Is there anything you can do for a sibling, I suspect 90% of the time it will be siblings.
Kaskade
A: 

Why not add the event listener inside the iframe and then call the parent / opener to notify the event.

If you the contents of the iframe is on a different domain, you won't be able to perform this as it is classed as "click-jacking", which was a big security threat.

Sohnee