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?


Solution 1:

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

Solution 2:

This works:

parent.$('body').trigger('eventName');

the event triggered inside the iframe will be detected in the parent document.

Solution 3:

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:

var myCustomData = { foo: 'bar' }
var event = new CustomEvent('myEvent', { detail: myCustomData })
window.parent.document.dispatchEvent(event)

And add this in the parent file which contains the iframe:

window.document.addEventListener('myEvent', handleEvent, false)
function handleEvent(e) {
  console.log(e.detail) // outputs: {foo: 'bar'}
}

Solution 4:

I have also find my way to solve this problem with jquery:

in parent file:

<body>
        <iframe src="something.html"></iframe>

</body>

<script>
 window.document.addEventListener('event', function(e){
            console.log("event:" + e.detail);
            $("iframe").contents().find(".class[title='" + e.detail + "']").css(someChanges);
</script>

so you don't need to add any other EventListener in your iFrames.

of course maybe you want see my CustomEvent:

var test  = "1";
var event = new CustomEvent('event', { detail: test })
                window.document.dispatchEvent(event);

I hope I could help somebody...