Trigger Custom Event From Iframe To Parent Documen

2019-01-31 18:36发布

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?

3条回答
【Aperson】
2楼-- · 2019-01-31 19:16

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'}
}
查看更多
冷血范
3楼-- · 2019-01-31 19:17

This works:

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

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

查看更多
狗以群分
4楼-- · 2019-01-31 19:19

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;  
        } 
    }
    
查看更多
登录 后发表回答