Cross-browser HTML5 postMessage method and message Event Simulation Implementation

Source: Internet
Author: User

PostMessage is a new HTML5 method that enables cross-domain window communication. So far, only IE8 +, Firefox 3, Opera 9, Chrome 3, and Safari 4 are supported. This article mainly describes the cross-browser implementation of the postMessage method and message event.

The postMessage method JSONP has different technologies. The former is the frontend that is good at cross-Origin document data instant communication, and the latter is good at cross-origin server data communication. The postMessage Application Scenario can illustrate this difference:

Use Cases
1. webOS uses iframe to embed it into a third-party application. In this case, webOS and the application need to receive/send their own messages and response events in real time.
2. An iframe layer is displayed and embedded in the Image Upload page provided by a third party. After the file is uploaded, You need to obtain the returned image address and insert it to the editor.
3. iframe cross-origin highly adaptive.
HTML5 postMessage Method
PostMessage enables Cross-Origin Document message transmission ).

Send messages to external windows:

1 otherWindow. postMessage (message, targetOrigin );
OtherWindow: refers to the target window, which is a member of the window. frames attribute or a window created by the window. open method.

Parameter description:

Message: the message to be sent. The type is String or Object (not supported by IE8 or 9)
TargetOrigin: Specifies the message receiving range. '*' is not restricted '*'
HTML5 message event
Bind a message event:

The Code is as follows: Copy code

Window. addEventListener ('message', receiver, false );
Function Cycler (event ){
If (event. origin = 'HTTP: // www.bkjia.com '){
If (event. data = 'Hello World '){
Event. source. postMessage ('hello', event. origin );
} Else {
Alert (event. data );
};
};
};

The first parameter of the callback function receives the Event object, which has three common attributes:

Data: Message
Origin: Message Source Address
Source: source DOMWindow object
Message event simulation in earlier browsers
Browsers that support the postMessage method directly use it. For IE6 and 7, a mature window. name is used to store data and a dynamic Cross-domain iframe static proxy transmission scheme, which is referred to as Cross Frame.

Cross Frame

Suppose there is a page a.html and a proxy page proxy-a.html on domain www.a.com, and another domain www. B .com has a page B .html and a proxy page proxy-b.html,when a.html needs to send messages to B .html, the page creates a hidden iframe pointing to the proxy-b.html and assigns the message to iframe. name property, in which case the proxy-b.html can pass through window. name gets the message, because the proxy-b.html and B .html are the same domain, proxy-b.html can give the message B .html. B .html uses the same principle when sending messages to a.html.

Automatically capture proxy URLs

In the Cross Frame scheme, both parties must know the URL of the static proxy file exactly. Obviously, this greatly limits the application scope and can be improved through some conventions: static proxy files must be placed in the domain root directory where the communication page is located, and the file names must be consistent, such as messageEvent-proxy.html.

With the above conventions, we can use some clever methods to allow both parties to automatically capture the proxy URL. The http://www.a.com/a.html is embedded into the http://www. B .com/ B .html through iframe to keep the data exchange as an example to explain:

B .html's static proxy path can be analyzed through regular expressions iframe. after src, it is difficult to obtain the parent page from the Framework B .html, because the parent after cross-origin. location. the href attribute can only be written and cannot be read, but can also be borrowed from document. the referrer attribute is used to analyze the origin address to learn the url of the parent page. Document. referrer is an unstable attribute. We can use the window. name refresh feature in iframe to save the.html address of the parent page.

Continuous tracking URL

A.html extracts the iframe. src path for the first time to learn the B .html address. If B .html jumps to another domain name, it will lose contact with the static proxy in iframe. Fortunately, the new page can get the parent page a.html and save it in the window. name static proxy, so we can send a message to a.html at the initialization of the new page to tell it the new address, so that we can continuously track the URL in iframe.

Open-source event library messageEvent. js
"MessageEvent. js is a message Event encapsulated in the preceding scheme and a postMessage producer library. It makes the event object member attributes of the message between browsers uniform, Event. the data property delivers up to 2 MB of text information, and enables IE6-9 browsers to support Object-type data transfer like other modern browsing (using deep copy internally ).

If both applications use messageEvent. js, cross-origin communication can be easily implemented.

Interface

Add (callback) add message event
Remove (callback) uninstall message event
PostMessage (otherWindow, message, targetOrigin) sends messages to the external window
Use it with jQuery

JQuery is a widely used DOM library. Its event mechanism is very powerful and exquisite, and it can implement custom events. If the page references jQuery, messageEvent. js will provide support for it. You can use familiar jQuery api-style programming, such:

The Code is as follows: Copy code

JQuery (window). bind ('message', function (event ){
Alert (event. data)
});

JQuery (window). message (function (event ){
Alert (event. data)
});

JQuery. postMessage (iframe. contentWindow, 'Hello world ','*');

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

JQuery uses the data property of the encapsulated Event object to save the additional data passed in by the bind method, causing conflict with the event. data Attribute of the message Event itself-this is a design error. To allow message events to correctly obtain event. data, messageEvent. js forcibly overwrites the additional data passed in by the bind method by operating the jQuery underlying cache (only for the message type ). Of course, I still expect jQuery to cancel the bind feature in future versions.


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.