Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Custom Event From Iframe To Parent Document

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?

like image 816
Marco C Avatar asked Oct 19 '12 04:10

Marco C


People also ask

How do I pass an iframe event to parent?

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.

Can iframe access parent document?

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.

Can you interact with iframe?

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.

Do iframe events bubble?

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.


1 Answers

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):

  1. Add an event listener as you normally would

     window.addEventListener('message', handleMessage, false); 
  2. 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;        }   } 
like image 142
Ryan Safarian Avatar answered Sep 28 '22 18:09

Ryan Safarian