4

I have a simple iFrame … 

<iframe src="url" width="980px" height="90px" id="inviteFrame" name="inviteFrame" scrolling="no"></iframe>

I know I can't catch click events on elements inside the frame but how about a simple click or mousedown on the iFrame itself?

$('#inviteFrame').click(function() {
    console.log('test');
    $(this).attr('height', '140px');
});

This doesn't work for me!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
matt
  • 42,713
  • 103
  • 264
  • 397
  • 1
    Do you display a page from **your server** in `iframe`? – VisioN May 13 '12 at 13:43
  • Actually yeah, from a subdomain of my page. So I'm on "url.com" and the iframe src is "subdomain.url.com" … right now i'm locally and just wonder how I can catch a click event when clicking on it. – matt May 13 '12 at 13:52

2 Answers2

7

jQuery has a method, called .contents(), that when used on an iframe element returns the document of the iframe.

// Get a reference to the iframe document
var iframeDoc = $('#inviteFrame').contents().get(0);

Now you can bind an event to it, get the dimensions, get styles of various elements, etc:

// Get width of iframe document
$(iframeDoc).width();

// Get height of iframe document
$(iframeDoc).height();

// Bind event to iframe document
$(iframeDoc).bind('click', function( event ) {
    // do something
});

// Get the style of an element in the iframe
$('div', iframeDoc).css('backgroundColor');
Zuul
  • 16,217
  • 6
  • 61
  • 88
  • 1
    This does of course only work if the iframe content is from the same domain, right? – matt May 13 '12 at 13:57
  • Does it also work for iframe from 3rd party? It seems not according to my test. – clwen Jan 04 '13 at 03:18
  • 1
    @clwen If the Iframe comes from a different domain, it will not work due to the jQuery's cross-domain request handling. You can try to force cross-site scripting (as of jQuery 1.5) using: `jQuery.support.cors = true;`. You can view the documentation [here](http://api.jquery.com/jQuery.support/). – Zuul Jan 04 '13 at 12:35
1

You cannot do this because of web browser's same origin policy.

But you can use a workaround with the blur event and mouseover/mouseout events. That's how works my iframeTracker jQuery plugin, designed to track clicks on iframes : https://github.com/finalclap/iframeTracker-jquery

Here is an example :

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});

Enjoy !

Vince
  • 3,274
  • 2
  • 26
  • 28
  • Hi @Vince, I'm using your plugin for something like this but having some problems. Can you offer any help on my other question here? http://stackoverflow.com/questions/25891050/accuratly-catch-clicks-on-an-iframe – tripRev Sep 17 '14 at 12:50