Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

What are the MessageChannel and MessagePort Objects in HTML5?

With HTML5, what is the role of MessageChannel and MessagePort Objects for message channel?



1 Answer
Krantik Chavan

While creating messageChannel, it internally creates two ports to sending the data and forwarded to another browsing context.

  1. postMessage() − Post the message throw channel
  2. start() − It sends the data
  3. close() − it close the ports

In this scenario, we are sending the data from one iframe to another iframe. Here we are invoking the data in function and passing the data to DOM.

var loadHandler = function(){
   var mc, portMessageHandler;
   mc = new MessageChannel();
   window.parent.postMessage('documentAHasLoaded','https://foo.example',[mc.port2]);
   
   portMessageHandler = function(portMsgEvent){
      alert( portMsgEvent.data );
   }
   mc.port1.addEventListener('message', portMessageHandler, false);
   mc.port1.start();
}
window.addEventListener('DOMContentLoaded', loadHandler, false);
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.