Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's difference between web-messaging with MessageChannel and without?

Using html5 I can do this:

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

Or I can use MessageChannel:

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

What's real difference between this two ways? When I must use the first variant and when I must use the second variant?

like image 824
mtkachenko Avatar asked Sep 21 '13 14:09

mtkachenko


1 Answers

I doubt I could explain it better than the following, however the important point is that once the port has been sent over, there's no origin checks that needs to occur for subsequent messages. When using window.addEventListener('message', ...), you have to validate that the message source is trusted everytime you recieve a 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

like image 64
plalx Avatar answered Oct 21 '22 15:10

plalx