Monday 20 April 2015

Web Messaging or cross-document messaging

Web Messaging or cross-document messaging, is an API introduced in the WHATWG HTML5draft specification, allowing documents to communicate with one another across different origins, or source domains


Example[edit]

Consider we want document A located on example.net to communicate with document B located on example.com, which is contained within an iframe or popup window.[1] The JavaScript for document A will look as follows:
var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello B', 'http://example.com/');
The origin of our contentWindow object is passed to postMessage. It must match the origin of the document we wish to communicate with (in this case, document B). Otherwise, a security error will be thrown and the script will stop.[3] The JavaScript for document B will look as follows:
function receiver(event) {
 if (event.origin == 'http://example.net') {
  if (event.data == 'Hello B') {
   event.source.postMessage('Hello A, how are you?', event.origin);
  }
  else {
   alert(event.data);
  }
 }
}
window.addEventListener('message', receiver, false);
An event listener is set up to receive messages from document A. Using the origin property, it then checks that the domain of the sender is the expected domain. Document B then looks at the message, either displaying it to the user, or responding in turn with a message of its own for document A.[1]


http://en.wikipedia.org/wiki/Web_Messaging

No comments:

Post a Comment