Trigger Custom Event From Iframe To Parent Document

前端 未结 4 2241
别跟我提以往
别跟我提以往 2020-12-07 22:54

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,

4条回答
  •  再見小時候
    2020-12-07 23:24

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

提交回复
热议问题