HTML5 window/iframe cross-domain Messaging API introduction

Source: Internet
Author: User
Tags bind setinterval mootools port number

Window.postmessage allows multiple window/frame to pass data and information across domains. Here's how the Window.postmessage works and how to use it in Firefox,ie8+,opera,safari and chrome

 

Original address: html5′s window.postmessage API
Online Example: Using HTML5 ' s window.postmessage (please open the console to see log)

I wrote a MooTools plugin "Postmessager" to encapsulate Window.postmessage, you can click here to download!

HTML5 's Window.postmessage interface API is not yet known to many people. Window.postmessage allows multiple window/frame to pass data and information across domains. Essentially Window.postmessage plays a cross-domain Ajax request role, of course, and does not require a remote server to collaborate. The next step is to explain how window.postmessage works and how to use it in Firefox,ie8+,opera,safari and Chrome.

One, the message sends the end
The first step in the process is to set up a "message source." With this message source, we can send window-level data (messages) to a newly opened window (or IFRAME). In the following example, messages are sent to a new window every 6 seconds, and event sniffing is set up to handle the response information returned by the target window.

Copy Code code as follows:


function Trace (message) {


var infos = Array.prototype.slice.call (arguments,0). Join ("");


if ("Console" in window) {


Console.log (infos);


} else {


alert (infos);


}


};


//Create pop-up window


var domain = ' http://scriptandstyle.com ';


var mypopup = window.open (domain + '/windowpostmessagelistener.html ', ' Mywindow ');


//timed Send message


setinterval (function () {


var message = ' Now time: ' + (new Date (). GetTime ());


Trace (' data source. Messages Sent: ' + message ');


mypopup.postmessage (Message,domain); Send the data information and set the target URI


},6*1000);


function Bindevent (target,nooneventname,handler) {


if (window.addeventlistener) {


Target.addeventlistener (Nooneventname,handler);


} else if (window.attachevent) {


//IE's listener Setup function is attachevent


target.attachevent ("on" +nooneventname,handler);


} else {


target["on" +nooneventname]=handler;


}


};


Listen for incoming information.


bindevent (window, ' message ', function (event) {


//Only receive messages for a specific domain


if (event.origin!== ' http://scriptandstyle.com ') return;


Trace (' Received response information: ', event.data);


},false);


The original author uses the Window.addeventlistener method to bind the event, but under IE will be an error (ie is window.attachevent). Of course, you can create functions to wrap events, or use ready-made class libraries, such as MooTools or Jquery/dojo to achieve.
In the example above, if the new window is open, we can send the message through a reference to the Window object and specify the URI (protocol, host name, port number) that must match (the message will not be sent if the user jumps to another page in the Mypopup).
We also bind the event handler function to receive message messages. In this reminder, it is important to verify the origin (source) attribute of the message event, because it is possible to receive messages from all URIs that are not confused when multiple frame interactions. After Origin is checked, how to handle this message depends on your specific business and requirements.

If you use IFRAME, then the code is as follows:

Copy Code code as follows:


//also creates another window (Iframe,frame,frameset,top,window these all belong to window-related objects.) )


var domain = ' http://scriptandstyle.com ';


var iframe = document.getElementById (' Myiframe '). Contentwindow;


//Loop Send message, of course, can also use event-driven ...


SetInterval (function () {


var message = ' Now time: ' + (new Date (). GetTime ());


Trace (' data source. Messages Sent: ' + message ');


iframe.postmessage (Message,domain); Send the data information and set the target URI


},6*1000);


Make sure that you have access to the Contentwindow properties of the IFrame object-not just the IFrame object.

second, the message receiving end
The second step in the entire process is to get the target window ready. The purpose window is to listen for the message event and, of course, to verify the origin source of the event. Reminder again: The message event handler can accept any messages sent to him by any domain name, so it is important to verify origin and to process only the information for the trust list.

Copy Code code as follows:


//Listen for incoming information.


bindevent (window, ' message ', function (event) {


//Only receive messages for a specific domain


if (event.origin!== ' http://davidwalsh.name ') return;


trace (' Monitor message: ', event.data);


//Reply message


event.source.postMessage ("Hello, little friends, I have received the message, Event.origin);"


},false);

The example above in


replies to the response information to the requesting party.
Message events are important attributes:
Source-The Window/iframe object that sends the messages
origin-corresponds to the URI that sends the Word window (protocol, domain, and port, If so,
data-specific information
for the message system and for checksums, these three objects are essential.

window.postmessage Use considerations
As with all other web technologies, the danger is obvious if used improperly (no validation event source). Of course, security is your own guarantee.
Window.postmessage is much like PHP in JavaScript technology (haha, small ads!) Window.postmessage is a cool technique, don't you think?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.