HTML5window/iframe cross-origin message passing API introduction _ html5 tutorial skills-

Source: Internet
Author: User
Tags mootools
Window. postMessage allows multiple windowframes to transmit data and information across domains. The following describes how window. postMessage works and how to use the original address HTML5's window. postMessage API in FireFox, IE8 +, Opera, Safari, and Chrome.
Online example: Using HTML5's window. postMessage (open the console to view logs)

I wrote a MooTools plug-in "PostMessager" to encapsulate window. postMessage. You can click here to download it!

Not many people know about the HTML5 window. postMessage API. Window. postMessage allows cross-origin transmission of data and information between multiple Windows/frames. In essence, window. postMessage plays the role of a cross-origin Ajax request. Of course, remote servers are not required to collaborate. Next we will introduce how window. postMessage works and how to use it in FireFox, IE8 +, Opera, Safari, and Chrome.

I. message sender
The first step in the process is to set an "Source ". With this message source, we can send window-level data (messages) to the newly opened window (or iframe ). In the following example, a message is sent every 6 seconds to a new window, and an event listener is set to process the response information returned by the target window.

The Code is 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 a dialog box
Var domain = 'HTTP: // scriptandstyle.com ';
Var myPopup = window. open (domain + '/windowPostMessageListener.html', 'mywindow ');
// Send messages regularly
SetInterval (function (){
Var message = 'current time: '+ (new Date (). getTime ());
Trace ('data source. sent message: '+ message );
MyPopup. postMessage (message, domain); // send 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 ){
// The Listener setting function of IE is attachEvent.
Target. attachEvent ("on" + noOnEventName, handler );
} Else {
Target ["on" + noOnEventName] = handler;
}
};
// Listen for received information.
BindEvent (window, 'message', function (event ){
// Only receive messages from a specific domain
If (event. origin! = 'HTTP: // scriptandstyle.com ') return;
Trace ('Received Response Message: ', event. data );
}, False );


The original author uses window. the addEventListener method is used to bind events, but an error will be reported in IE (IE is window. attachEvent ). of course, you can create a function to wrap events, or use a ready-made class library, such as MooTools or jQuery/dojo.
In the above example, if the new window is opened normally, we can send a message using the reference myPopup of the window object and specify the URI (protocol, host name, and port number) That must be matched) (If the user jumps to another page in the subwindow, the message will not be sent ).
We also bound an event processing function to receive the message. It is important to verify the origin (source) attribute of the message event, because it may receive messages sent to itself from all Uris and will not be confused during interaction between multiple frames. After verifying the origin, how to handle this message depends on your specific business and needs.

If iframe is used, the Code is as follows:

The Code is as follows:


// Create another window (iframe, frame, frameset, top, and window all belong to window-related objects .)
Var domain = 'HTTP: // scriptandstyle.com ';
Var iframe = document. getElementById ('myiframe'). contentWindow;
// Send messages cyclically. Of course, you can also use event-driven messages...
SetInterval (function (){
Var message = 'current time: '+ (new Date (). getTime ());
Trace ('data source. sent message: '+ message );
Iframe. postMessage (message, domain); // send data information and set the target URI
}, 6*1000 );


Make sure that you can access the contentWindow attribute of the iframe object, not just the iframe object.

Ii. Message receiving end
The second step of the entire process is to make the target window ready. All you need to do in the target window is to listen to the message event, and verify the origin message source of the event. Reminder again: the message event processing function can accept messages sent from any domain name, so it is very important to verify the origin and only process the message in the trust list.

The Code is as follows:


// Listen for received information.
BindEvent (window, 'message', function (event ){
// Only receive messages from a specific domain
If (event. origin! = 'HTTP: // davysh. name') return;
Trace ('listening to information: ', event. data );
// Reply to the message
Event. source. postMessage ("" Hello, friends, I have received the message, event. origin );
}, False );


The above example replies the response to the requester.
Important attributes of message events include:
Source-the window/iframe object that sends the message
Origin-corresponds to the URI (protocol, domain, and port, if specified) of the message sending window)
Data-specific data information
For message systems and verification, these three objects are essential.

Window. postMessage usage considerations
Like all other Web technologies, the danger of improper use (with no event source verified) is obvious. Of course, security is guaranteed by yourself.
Window. postMessage is like PHP In JavaScript technology (haha, small advertisement !). Window. postMessage is a cool technology. What do 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.