Trigger Custom Event From Iframe To 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):

  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;  
         } 
     }
    

Leave a Comment