Cross-browser HTML5 PostMessage method and message event simulation implementation

Source: Internet
Author: User
Tags file upload domain server

PostMessage method JSONP Technology is different, the former is good for Cross-domain document data real-time communication, the latter is good at Cross-domain server-side data communication, PostMessage application scenario can illustrate this difference:

Examples of application scenarios
1.webOS uses IFRAME to embed third party applications, when WebOS and applications need to receive/send their respective messages and response events in real time.
2. Page pop-up by the IFRAME layer, embedded in the third party to provide a picture upload page, file upload after the need to get back to the picture address inserted into the editor.
3.iframe is highly adaptive across domains.
HTML5 PostMessage method
PostMessage can implement message transfer across domain documents (Cross document messaging).

To send a message to an outside window:

1 otherwindow.postmessage (message, targetorigin);
Otherwindow: Refers to the target window, a member of the Window.frames property or a window created by the Window.Open method

Parameter description:

Messages: is the message to send, type String, Object (IE8, 9 not supported)
Targetorigin: is a limited message receive range, no limit please use ' * '
HTML5 Message Event
To bind a message event:

The code is as follows Copy Code

Window.addeventlistener (' message ', receiver, false);
Function Receiver (event) {
if (Event.origin = = ' Http:// ') {
if ( = = ' Hello world ') {
Event.source.postMessage (' Hello ', event.origin);
} else {
alert (;

The first parameter of the callback function receives the Event object, and there are three common properties:

Data: Message
Origin: Message Source Address
Source: Domwindow Object
The message event is simulated in a low version browser
For the browser that supports the PostMessage method, it is used directly, but for IE6, 7 uses the more mature to save the data and the Cross-domain IFRAME static proxy dynamic transmission scheme, hereinafter referred to as Cross Frame.

Cross Frame

Assuming that there are page a.html and proxy page proxy-a.html on the domain, and there is a page b.html and proxy page on another domain proxy-b.html,a.html need to send a message to b.html, the page Creates a hidden iframe pointing to proxy-b.html and assigns the message to the property, at which point proxy-b.html can get the message through, because proxy-b.html and b.html are the same domain , proxy-b.html can give the message to b.html. b.html to send a message to a.html, the principle is the same.

Auto Capture Agent URL

In the Cross Frame scheme, the communication both sides must know exactly the URL of the static proxy file, obviously this greatly limits the scope of application, we can improve by some conventions: static proxy files must be placed in the domain root of the communication page, and the file name must be consistent, as Messageevent-proxy.html.

With the above conventions, there are some ingenious ways to let both parties automatically capture the proxy URL. Taking through the IFRAME embedding to keep the data exchange as an example to illustrate:

The static proxy path of b.html can be learned by regular analysis iframe.src, and getting the parent page from the frame b.html is cumbersome because the Parent.location.href property after the Cross-domain can only be written unreadable, but can also borrow Document.referrer property to parse the routing address to learn the parent page URL. Document.referrer is an unstable attribute that we can use to save the address of the parent page a.html by using an refresh that does not change in the IFRAME.

Persistent Trace URL

A.html the first time by extracting iframe.src path can be learned b.html address, if the b.html jump to other domain names, this time will lose the static agent in the IFRAME contact. Fortunately, the new page will be able to get the parent page a.html saved in the static agent, so we can in the new page initialization when the message to a.html to tell it the new address, so you can continue to track the URL in the IFRAME.

Open Source Event Library Messageevent.js
"Messageevent.js" is the message event and the PostMessage method library encapsulated in the above scenario, which unifies the Event object member properties of messages between each browser, and attributes can pass up to 2MB of text information and It also enables ie6-9 browsers to support Object-type data delivery (internal use of deep copy) like other modern browsing.

Cross-domain communication is easy to implement if both sides of the application page adopt Messageevent.js.


Add (callback) adding a message Event
Remove (callback) Uninstall message Event
PostMessage (otherwindow, message, Targetorigin) sends messages to the external window
Use it through JQuery

JQuery is a widely used DOM library, its event mechanism is very powerful and subtle, can implement custom events. If the page references jquery, Messageevent.js will provide support for it, and you can program it in a familiar jquery API style, such as:

The code is as follows Copy Code

JQuery (window). Bind (' message ', function (event) {
Alert (

JQuery (window). Message (function (event) {
Alert (

Jquery.postmessage (Iframe.contentwindow, ' Hello World ', ' * ');

JQuery (window). Unbind (' message ');

Because JQuery saves the wrapped event object with the Data property to save the additional information passed in by the Bind method, it conflicts with the property of the message event itself-a design error. In order for the message event to be properly fetched,messageevent.js the additional data passed in by the Bind method (only for the message type) is enforced by manipulating the jQuery underlying cache. Of course, I'm still looking forward to a future version of JQuery that will cancel out the chicken feature of the Bind method.

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: 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.