gpt4 book ai didi

javascript - 使用 MessageChannel 和不使用 MessageChannel 的网络消息传递有什么区别?

转载 作者:行者123 更新时间:2023-11-28 01:53:01 25 4
gpt4 key购买 nike

使用 html5 我可以做到这一点:

document.getElementById('someIframe').contentWindow.postMessage('hi', 'someDomain');

或者我可以使用 MessageChannel:

var mc = new MessageChannel();
document.getElementById('someIframe').contentWindow.postMessage('hi', 'someDomain',[mc.port2]);

这两种方式之间的真正区别是什么?什么时候必须使用第一个变体,什么时候必须使用第二个变体?

最佳答案

我怀疑我能比下面的解释更好,但重要的一点是,一旦端口被发送过来,就不需要对后续消息进行来源检查。使用 window.addEventListener('message', ...) 时,您必须在每次收到消息时验证消息源是否可信。

When you create a new MessageChannel object, it has two connected MessagePort objects (port1 and port2). One of the ports is sent to another window or frame, and messages can be sent and received without repeated origin checking that is needed when using window.postMessage. Validation of the origin of a port and messages need only be done when a port is sent to windows other than the one that created them. MessagePort simplifies the messaging process by sending and receiving messages through two (and only those two) connected ports. Messages are posted between the ports using postMessage. Since the ports will only accept messages between the connected ports, no further validation is required once the connection is established. MessageChannel enables asynchronous communication between IFrameElements, cross-domain windows, or same page communications. http://msdn.microsoft.com/en-us/library/windows/apps/hh441303.aspx

关于javascript - 使用 MessageChannel 和不使用 MessageChannel 的网络消息传递有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18934027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com