I am having some trouble to fire a custom event inside an iframe and detect it from the parent document. Both iframe and parent document have the same origin (same protocol, same host, same port).
Any advises?
you can call parent. functionname() from your iframe. what if parent window is in different domain, then cannot raise events on parent window from child iframes.
It's still possible to access the parent from within a frame provided that the domains match. The variables parent and top can be overwritten (usually not intended). It's safer to use window.
All you have to do is first dispatch an event from the iframe to the parent that notifies the parent that the iframe is loaded (essentially a "ready message"). The parent will be listening for messages and if it receives the "ready message" event, it can then reply to the iframe with whatever message you want to send.
The iframe is a separate document tree, and so events that bubble through its tree terminate at the root of the iframe's document and do not travel across the boundary into the host document. This upward propagation will continue up to and including the Document.
I ran into a similar problem and used window.postMessage
to solve.
Currently, the API only supports passing a string, but if you modify your solution it can be powerful. More details here
From the source page (being consumed by an iframe):
postMessage API expects 2 params - message , target
ex: window.parent.postMessage("HELLO_PARENT", 'http://parent.com');
From the parent page (contains iframe. Eg Container):
Add an event listener as you normally would
window.addEventListener('message', handleMessage, false);
Define your function with event.origin check (for security) \
function handleMessage(event) { if (event.origin != "http://child.com") { return; } switch(event.data) { case "HELLO_PARENT": alert("Hello Child"); break; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With