HTML5 PostMessage resolving cross-domain, cross-window message delivery

Source: Internet
Author: User
Tags object getcolor return string version window domain port number

Usually do web development when about message delivery, in addition to the client and the server to pass the value of a few often encountered problems

1. Data transfer of the page and its open new window

2. Message passing between multiple windows

3. Page and nested IFRAME message delivery

4. Cross-domain data transfer for three above issues
PostMessage ()

There are some solutions to these problems, but HTML5 's introduction of the message API makes it easier, more effective, and more secure to solve these challenges. The PostMessage () method allows scripts from different sources to communicate in a limited manner asynchronously, allowing for cross text files, multiple windows, and Cross-domain message delivery.

PostMessage (Data,origin) method accepts two parameters

1.data: The data to be passed, mentioned in the HTML5 specification can be any basic type of JavaScript or a replicable object, but not all browsers do this, and some browsers can only handle string parameters. So we need to use the Json.stringify () method to serialize the object parameter when passing the parameter, and the reference json2.js in the low version IE can achieve similar effect.

2.origin: String parameter, indicating the source of the target window, protocol + host + port number [+url],url will be ignored, so you can not write, this parameter is for security reasons, PostMessage () method will only pass message to the specified window. Of course, if you like, you can also set the parameter to "*", which can be passed to any window, if you want to specify the same as the current window is set to "/".

Http://test.com/index.html

<div style= "width:200px; Float:left; Margin-right:200px;border:solid 1px #333; " >
<div id= "Color" >frame color</div>
</div>
<div>
<iframe id= "Child" src= "http://lsLib.com/lsLib.html" ></iframe>
</div>



We can pass messages http://lsLib.com/lsLib.html the PostMessage () method to cross-domain iframe pages in http://test.com/index.html

Window.onload=function () {
Window.frames[0].postmessage (' GetColor ', ' http://lslib.com ');
}

Receive Message

test.com The above page sends a message to lslib.com, then how to receive the message on the lslib.com page, listening to the window messages event can

Http://lslib.com/lslib.html

Window.addeventlistener (' message ', function (e) {
if (e.source!=window.parent) return;
var Color=container.style.backgroundcolor;
Window.parent.postMessage (color, ' * ');
},false);



So we can receive messages from any window, and for security reasons, we use this Messageevent object to judge the source of the message, Messageevent is a

There are several important attributes

    1. data: As the name suggests, is the message passed
    2. source: The Window object that sends the message
    3. Origin: Source (protocol + host + port number) for sending message window

This allows you to receive cross-domain messages, and we can send messages back, in a similar way

A simple Demo

In this example, the div on the left will vary according to the color of the div in the right iframe.

<!
DOCTYPE html>  
<!doctype html>  

In the example when the page is loaded, the home page faces the iframe to send ' GetColor ' requests (parameters are not practical)

Window.onload=function () {
Window.frames[0].postmessage (' GetColor ', ' http://lslib.com ');
}



The IFRAME receives the message and sends the current color to the main page.

Window.addeventlistener (' message ', function (e) {
if (e.source!=window.parent) return;
var Color=container.style.backgroundcolor;
Window.parent.postMessage (color, ' * ');
},false);



The main page receives the message and changes its div color

Window.addeventlistener (' message ', function (e) {
var color=e.data;
document.getElementById (' Color '). Style.backgroundcolor=color;
},false);



When clicking on the IFRAME triggers its discoloration method, send the latest color to the main page

function ChangeColor () {                             var color=
Container.style.backgroundColor;                 if (color== ' RGB 204, 102, 0) ' {                
    color= ' RGB (204, 204, 0) ';                }else{                     color= '
RGB (204,102,0) ';                }    
             Container.style.backgroundcolor=color;                 window.parent.postMessage (color, ' * ');            }

Home page or use the program that just listens to the message event to process its own discoloration

Window.addeventlistener (' message ', function (e) {
var color=e.data;
document.getElementById (' Color '). Style.backgroundcolor=color;
},false);


At last

The simple usage solves the big problem, and it is said that Facebook is already in use, and this is also the way to HTML5 another api--web workers the message, so what about its browser compatibility? The so-called browser compatibility has almost become ie a few beginning to support the problem ... But the good news is that like Localstorage, ie8+ all support, but some browsers of the lower version (such as FireFox4.0) does not support Window.onmessage=function () {} This way, so I'd better use event binding , in order to be compatible with IE, also to determine whether to support AddEventListener.



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.