javascript 从父级到子级 iframe 进行跨域通信

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19011780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:03:25  来源:igfitidea点击:

Communicating cross-origin from parent to child iframe

javascripthtmlpostmessage

提问by Benmj

I'm working through Third Party Javascript. I'm particularly interested in communication between a parent page and a child frame from a different origin. Using window.postMessage, it's trivial to safely send messages from the child and have the parent receive them with the messageevent.

我正在通过第三方 Javascript 工作。我对父页面和来自不同来源的子框架之间的通信特别感兴趣。使用 window.postMessage,安全地从子进程发送消息并让父进程通过message事件接收它们是微不足道的。

I have had no luck going the other direction. Can I get some confirmation that it is notpossible to communicate from the parent to the child using postMessage? If not what are ways of working around this problem?

我没有运气去另一个方向。我是否可以确认无法使用 postMessage 从父级到子级进行通信?如果不是,有什么方法可以解决这个问题?

回答by jfriend00

You should be able to use .postMessage()between any two cooperating windows. It doesn't matter which direction you are sending the message. If it is not working in one direction, then there is probably an error in the implementation. You may need to make sure you have the proper window object.

您应该能够.postMessage()在任何两个协作窗口之间使用。您发送消息的方向无关紧要。如果它不是在一个方向上工作,那么实施中可能存在错误。您可能需要确保拥有正确的 window 对象。

For an iframe, you would want to use the .contentWindowproperty to get its window in modern browsers.

对于 iframe,您可能希望使用该.contentWindow属性在现代浏览器中获取其窗口。

Some good documentation here: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

这里有一些很好的文档:https: //developer.mozilla.org/en-US/docs/Web/API/window.postMessage