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 source (same protocol, same host, same port).
Any advises?
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 source (same protocol, same host, same port).
Any advises?
A consistent answer supporting both same-domain and cross-domain iframes is to use event system.
The goal is to send a custom event from iframe to parent.
In the iframe source file:
And add this in the parent file which contains the iframe:
This works:
the event triggered inside the iframe will be detected in the parent 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
Define your function with event.origin check (for security) \