Click-event on iframe?

I have a simple iFrame ...

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

I know I cannot catch click events on elements inside a frame, but what about a simple click or mousedown on an iFrame itself?

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

This does not work for me!

+3
source share
2 answers

jQuery has a method . contents () , which when used in an iframe element returns an iframe document.

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

Now you can associate an event with it, get 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'); 
+7
source

You cannot do this due to the web browser of the same origin policy .

But you can use a workaround with blur events and mouseover / mouseout events. This works with 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 it!

+1
source

All Articles