HTML5 PostMessage resolving cross-domain, cross-window messaging

Source: Internet
Author: User
Tags getcolor

Transferred from: http://www.cnblogs.com/dolphinX/p/3464056.html

Usually do web development time about message delivery, in addition to client and server values there are several frequently encountered problems

1. Data passing 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 of the above three issues

PostMessage ()

There are some solutions to these problems, but the message API introduced by HTML5 can solve these problems more conveniently, effectively and safely. The PostMessage () method allows scripts from different sources to communicate in an asynchronous manner with limited communication, allowing for cross-text, multi-window, cross-domain messaging.

PostMessage (Data,origin) method accepts two parameters

1.data: To be passed, the HTML5 specification mentions that the parameter can be any basic type or replicable object of JavaScript, but not all browsers do craved, and some browsers only handle string parameters. So we need to use the Json.stringify () method to serialize the object parameters when we pass the parameters, and a similar effect can be achieved by referencing Json2.js in the low version of IE.

2.Origin: String parameter, indicating the source of the target window, protocol + host + port number [+url],url will be ignored, so can not write, this parameter is for security reasons, the PostMessage () method will only pass the message to the specified window, Of course, if you want to, you can set the parameters 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 to the cross-domain IFrame page http://lsLib.com/lsLib.html in http://test.com/index.html through the PostMessage () method

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

test.com The above page sends a message to lslib.com, how can I receive the message on the Lslib.com page, and listen to the window's message event

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 any message from any window, for security reasons, we use this time Messageevent object to judge the source of the message, messageevent is a such thing

There are several important properties

    1. data: As the name implies, is a message delivered
    2. source: The Window object that sent the message
    3. Origin: Source of the Sending message window (protocol + host + port number)

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

A simple Demo

In this example, the left Div will change depending on the div color in the right iframe.

<! DOCTYPE html>
<title>post message</title>
<body>
<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>

<script type= "Text/javascript" >

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

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

Http://test.com/index.html

<!doctype html>
<style type= "Text/css" >
html,body{
height:100%;
margin:0px;
}
</style>
<body style= "height:100%;" >
<div id= "Container" onclick= "ChangeColor ();" Style= "widht:100%; height:100%; Background-color:rgb (204, 102, 0); " >
Click to change color
</div>
<script type= "Text/javascript" >
var Container=document.getelementbyid (' container ');

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

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, ' * ');
}
</script>
</body>

Http://lslib.com/lslib.html

In the example page load when the homepage sends the ' GetColor ' request to the iframe (parameter is not useful)

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);

Main Page Receive message, change own div color

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

When clicking on an IFRAME to trigger 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, ' * ');            }

Main Page or using a program that has just listened 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, it is said that Facebook is already in use, and this is also html5 another api--web workers to pass the message method, then its browser compatibility how? The so-called browser compatibility has almost become the problem of IE several start support ... But the good news is like Localstorage, ie8+ support, but some of the low version of the browser (such as FireFox4.0) does not support the Window.onmessage=function () {} This way, so I'd better use the notation of event binding , in order to be compatible with IE, also want to judge whether support AddEventListener.

HTML5 PostMessage resolving cross-domain, cross-window messaging

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.