Html5 postMessage solution for cross-origin and cross-window message transmission, html5postmessage

Source: Internet
Author: User
Tags getcolor

Html5 postMessage solution for cross-origin and cross-window message transmission, html5postmessage

There are also several common problems about message passing during web development in addition to passing values between the client and server.

1. data transmission between the page and its new window

2. message transmission between multiple windows

3. webpage and nested iframe message transmission

4. Cross-Origin data transmission for the above three problems

PostMessage ()

There are some solutions to these problems, but the message API introduced by html5 can solve these problems more conveniently, effectively and securely. The postMessage () method allows scripts from different sources to communicate with each other in an asynchronous manner, and supports cross-text file, multi-window, and cross-origin message transmission.

The postMessage (data, origin) method accepts two parameters.

1. data:For the data to be transmitted, the html5 specification mentions that this parameter can be any basic type or replicated object of JavaScript. However, not all browsers have done this, some browsers can only process string parameters, so we need to use JSON when passing parameters. the stringify () method serializes object parameters. Similar effects can be achieved by referencing json2.js in earlier versions of IE.

2. origin:String parameter, indicating the source of the target window, protocol + host + port number [+ URL], URL will be ignored, so do not write, this parameter is for security consideration, postMessage () the method will only pass the message to the specified window. If you want to, you can also set the parameter to "*", so that the message can be passed to any window, if you want to specify the same source as the current window, set it "/".

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>

You can use the postmessage () method at http://test.com/index.htmlto send a message to the iframe page of the Cross-origin domain at http://lslib.com/lslib.html.

window.onload=function(){            window.frames[0].postMessage('getcolor','http://lslib.com');        }

Receive messages

The page above test.com sends a message to lslib.com, so how can I receive the message on the lslib.com page and listen to the message event of the window?

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

In this way, we can receive messages transmitted in any window. For the sake of security, we use the MessageEvent object at this time to determine the message source. MessageEvent is such a thing.

There are several important attributes

1. data:As the name implies, it is a message transmitted.

2. source:Window object for sending messages

3. origin:Source of the message sending window (Protocol + host + port number)

In this way, we can receive cross-origin messages. We can also send the messages back in a similar way.

Simple demo

In this example, the div on the left changes according to the div color in the iframe on the right.

<!DOCTYPE html>
<!doctype html>

In this example, when a page is loaded, the homepage sends a 'getcolor' request to iframe (the parameter is useless)

window.onload=function(){            window.frames[0].postMessage('getcolor','http://lslib.com');        }

Iframe receives the message and sends the current color to the homepage.

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

Receive messages on the home page and change the div color.

window.addEventListener('message',function(e){            var color=e.data;            document.getElementById('color').style.backgroundColor=color;        },false);

When you click iframe to trigger the color change method, send the latest color to the home 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,'*');            }

The home page still uses the program that just listened to the message event to process its own color change.

window.addEventListener('message',function(e){            var color=e.data;            document.getElementById('color').style.backgroundColor=color;        },false);

Last

The simple usage solves the big problem. It is said that Facebook is already in use, and this is another html5 API-web workers message transmission method. How is its browser compatibility? The so-called Browser compatibility has almost become a problem with IE support... However, the good news is that, like localStorage, IE8 + supports windows, but some earlier browsers (such as FireFox4.0) do not support windows. onmessage = function () {}, so I 'd better use the event binding method. To be compatible with IE, I also need to determine whether addEventListener is supported.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.