How to communicate between iframe and the parent site?

前端 未结 6 649
北海茫月
北海茫月 2020-11-22 13:01

The website in the iframe isn\'t located in the same domain, but both are mine, and I would like to communicate between the iframe and the pare

6条回答
  •  逝去的感伤
    2020-11-22 13:22

    It must be here, because accepted answer from 2012

    In 2018 and modern browsers you can send a custom event from iframe to parent window.

    iframe:

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

    parent:

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

    PS: Of course, you can send events in opposite direction same way.

    document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
    

提交回复
热议问题