Web Messaging to share data without Dom
Posted By : Sachin Arora | 25-Feb-2018
Web messaging is the way to share the data without Dom. It overrides the domain communication problem in different domains,protocols or ports.For Example if you want to send data from your page to an iframe container and vice-versa. In this case browser throws an exception ie security exception, with web messaging we can pass the data in form of message event.
Message events fires some event that are Cross-document messaging, server-sent events, channel messaging and web-sockets which are described by message event interface.
Attributes
1) Data - It contains string data.
2) Origin - It contains Port and Domain name.
3) Source - It contains a reference to the originating document's window.
4) Ports - It contains data which is sent by any message port.
5) lastEventId - It contains unique identifier for current message event.
Sending a Cross Document Message
Before sending a cross document message firstly we need to create a web browsing context either by creating a new iframe or new window.we can send our message by using the method called postMessage() which intakes two arguments, which are the message which we need to send and target origin ie where we want to send.
Examples:
sending message from iframe to button
var iframe = document.querySelector('iframe');
var button = document.querySelector('button');
var clickHandler = function(){
iframe.contentWindow.postMessage('The message to send.','https://www.xyz.com);
}
button.addEventListener('click',clickHandler,false);
Receiving a cross document message in receiving document
var messageEventHandler = function(event){
// check that the origin is one we want.
if(event.origin == 'https://www.xyz.com'){
alert(event.data);
}
}
window.addEventListener('message', messageEventHandler,false);
So this way we can use web messaging to share the data .
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sachin Arora
Sachin is ambitious and hardworking individual with broad skills,He have the capabilities to build captivating UI applications . One of his key strength is building a strong bond with the team in order to deliver the best results on time .