Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery trigger custom event in iframe window

I'm having trouble triggering a custom event in an iframe from the parent document.

In the child I have code like this:

$(window).on( 'my-event', function() { console.log( "GOT IT" ) } )

In the parent I get the iframe and try to send an event:

iframe = document.getElementById( 'content-frame' )
$(iframe.contentWindow).trigger( 'my-event' )

The event doesn't arrive. I've tried using 'document' instead of window, but still without luck.

Can this be done with jquery?

I'm hoping there is a simple way so I can avoid writing a dispatch function whereby the parent calls a function in the iframe and it dispatches the event.

like image 703
edA-qa mort-ora-y Avatar asked Feb 11 '14 18:02

edA-qa mort-ora-y


Video Answer


1 Answers

Here is my solution. In the parent, you can fire the event using the following:

$('#content-frame')[0].contentWindow.$('body').trigger('my-event');

In the child, you can listen for the event:

$('body').on('my-event', function(e) {
  alert("Hello, World! Message received!");
});
like image 129
Pete Avatar answered Oct 17 '22 09:10

Pete