communication between two iframe children using postMessage

前端 未结 1 878
北海茫月
北海茫月 2021-02-19 04:31

I have some embed code that users can put on their sites. It creates two children iframes on the page. I\'d like to have those children be able to communicate.

I\'m us

相关标签:
1条回答
  • 2021-02-19 05:14

    Why do you say that the child iframes can't communicate directly? Actually, they can. What you can do within a child iframe is use the window.parent property to get a reference to the parent window, and then use the parent's frames property to get references to all child iframes (the frames property gives you an array of such references). After that, you can use postMessage on each of those references, and set the required origin restrictoin in the postMessage call so that you are sure only the right iframe gets the message.

    Notice that this will work even when all three windows (iframe1, parent window and iframe2) are on different domains because iframe1 is not doing anything with the parent window (which would violate SOP), it is only fetching references to nested iframes.

    Links:

    https://developer.mozilla.org/en-US/docs/DOM/window.parent

    https://developer.mozilla.org/en-US/docs/DOM/window.frames

    0 讨论(0)
提交回复
热议问题