Trigger Custom Event From Iframe To Parent Documen

2019-01-31 19:06发布

问题:

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?

回答1:

This works:

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

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



回答2:

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 != "h ttp://child.com") { return; }  
        switch(event.data) {   
             case "HELLO_PARENT":  
                alert("Hello Child");  
                break;  
        } 
    }
    


回答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'}
}