Channel Messaging is the two way communication for the browsing contexts, which is a usable communication across multiple origins. If user can create a message channel it internally creates two ports for sending and forwarding to another browser context as shown below.
- postMessage()
Post the message by using channel.
- start()
Which sends the data.
- close()
Which close the ports.
The code below is used to start sending the data between the
iframes. Here user invoked the data function and also passed the data to the DOM.
[c]var loadHandler = function(){
var mc, portMessageHandler;
mc = new MessageChannel();
window.parent.postMessage('documentAHasLoaded','http://foo.example',[mc.port2]);
portMessageHandler = function(portMsgEvent){
alert( portMsgEvent.data );
}
mc.port1.addEventListener('message', portMessageHandler, false);
mc.port1.start();
}
window.addEventListener('DOMContentLoaded', loadHandler, false);
[/c]
The code below is used to demonstrate the data which came from the port 2 and is passed to the second iframe.
[c]var loadHandler = function(){
var iframes, messageHandler;
iframes = window.frames;
messageHandler = function(messageEvent){
if( messageEvent.ports.length > 0 ){
// transfer the port to iframe[1]
iframes[1].postMessage('portopen','http://foo.example',messageEvent.ports);
}
}
window.addEventListener('message',messageHandler,false);
}
window.addEventListener('DOMContentLoaded',loadHandler,false);
[/c]
The code below is used to demonstrate the
portMessageHandler function which is used by the second document.
[c]var loadHandler(){
// Define our message handler function
var messageHandler = function(messageEvent){
// Our form submission handler
var formHandler = function(){
var msg = 'add <foo@example.com> to game circle.';
messageEvent.ports[0].postMessage(msg);
}
document.forms[0].addEventListener('submit',formHandler,false);
}
window.addEventListener('message',messageHandler,false);
}
window.addEventListener('DOMContentLoaded',loadHandler,false);
[/c]