问题
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.
回答1:
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!");
});
回答2:
Just an addition to Pete's answer (jQuery is not required)
var event = document.createEvent('CustomEvent');
event.initCustomEvent('my-event', true, true, null);
frames['iframeId'].document.dispatchEvent(event);
a more verbose version:
var event = document.createEvent('CustomEvent');
var canBubble = true;
var cancelable = true;
var eventdDetail = {};
event.initCustomEvent('myEvents:myCustomEvent', canBubble, cancelable, eventDetail);
frames['iframeId'].document.dispatchEvent(event);
eventDetail
object is then available as the event handler's event.detail property
However this is an old syntax even though supported in all browsers.
In modern browsers it is advised to use the CustomEvent()
constructor.
initCustomEvent
documentation at MDN, at MSDN- CustomEvent() documentation for the new custom event object constructor (IE 9+)
来源:https://stackoverflow.com/questions/21709864/jquery-trigger-custom-event-in-iframe-window