[Html5_webworkers] Introduction to HTML5 Web Communication (cross-document communication/channel communication)

Source: Internet
Author: User
Tags event listener

A simple summary

Web Communication (Foreign name: Web messaging) is a document in which the DOM between separate browsing contexts is not exposed by malicious cross-domain scripting to the way data is shared.

Get, terminology ah what, than to see Sister Feng also headache. It is necessary to take the above sentence apart:

    • Web communication is a way of sharing data (with the suspicion of fart words);
    • The principal of the communication is the "browsing context" (This is Nani?). );
    • Oh, "browsing context" is "an environment where the Document object is presented to the user," you can approximate the context of a page that we see in the ordinary.
    • Web traffic does not have the risk of being maliciously exposed by the DOM;
    • At present, more applications are the communication between the IFRAME (this is my own extra).
If you see this text, you are using RSS to read or turn to "a Tree-blog park," The original address: http://www.cnblogs.com/atree/archive/2012/03/07/HTML5-Web-Messaging.html

When we talk about Web communications, we are actually talking about two slightly different systems: cross-document communication (cross-document messaging) and channel communication (channels messaging). Cross-document communication is the kind of communication that is more familiar in our domestic HTML5 window.postmessage () applications, and channel communication is also known as "Messagechannel". Along with the Server-sent event and the Web sockets, cross-document communication and channel communication became a useful part of the HTML5 Communication Interface "Suite".

Browser support (to 2012-02-27)
Web communications have been supported by opera, Chrome, and Safari, although the safari≤5.1.2 version has bugs. The IE8 section supports cross-document communication: Only communicates with the IFRAME and does not support new window communication. IE10 will support channel communication. Firefox currently supports cross-document information, but does not support channel communication.

II. Communication Events

The following event object is introduced here first message . Why?

Because, whether it is cross-document communication (cross-document messaging), channel communication (channels messaging), Server send events (server-sent events), or network sockets (Web sockets) are executed messageevent. So it helps to understand. Like whether you want to marry Lin or "wind fork Change People" elder sister, all want to pass your mother this, therefore, understand your mother's preference is very helpful!

The definition of the message event can be found here (this link suggests no point, English + term → Big head son), the event contains 5 read-only properties:

Data Contains arbitrary string data, sent by the original script
Origin A string that contains the schema of the original document, the domain name, and the port (for example: http://domain.example:80)
Lasteventid A string that contains the unique identifier of the current message event.
Source A reference to the original file's window. More precisely, it is a Windowproxy object.
Ports An array that contains any Messageport objects that send messages.

In cross-document communication and channel communication, lastEventId the value is generally an empty string, and the lastEventId application sends events on the server side. If there is no ports in the sending message, the ports property value is an array of length 0.

MessageEventInherits the DOM event interface and attributes are shared. However, the communication event does not bubble, cannot be canceled, and there is no default behavior.

Third, cross-document communication

The use of cross-document communication is similar to what we usually receive in real life. Send → receive.

The description of the text is not conducive to understanding. So let's start with an example.

The example is simple, on the page two iframe frame, the left side can enter the information, click the Confirmation button, the input information can be displayed in the IFRAME on the right.

You can really click here: cross-document communication between two IFRAME demo

For example, we enter "White is killed" on the left, click on the button, the right side of the corresponding display, see below:

As mentioned above, cross-document communication is supported by ie8+ browsers, so this demo is also effective under the IE8 browser:

OK, the above example is simple, send and receive!

Send the core JS code as follows:

Window.parent.frames[1].postmessage (Message, ' * ');

Description

  1. window.parent.frames[1]Refers to the second IFRAME in the demo page. Then use the postMessage method to send the data.
  2. postMessageMethods support two parameters, refer to the following table:
    Message The data sent
    Targetorigin The source of the sent data.

    In fact, there is an optional third parameter transfer , but used in the channel communication, this is put in the back.

    postMessageThe parameters in a method message can be not only strings, but also structural objects, data objects (such as: File and ArrayBuffer ), or arrays. Very powerful, but unfortunately, ie8/ie9/firefox3.6 and the following versions only support string data.

    targetOriginParameter refers to the source of the received document. The browser does not send a message unless the receiving information browsing context originates from targetOrigin a match in the provided. Of course, you can bypass this type of restriction, just like the demo above, and use "*" wildcards directly, but obviously this is exposing the Lord to the edge of the anti-thief (insecure information disclosure). This demo is designed to make it easier to understand and remove unwanted distractions, so "*" you use wildcards, and you must specify the target source when you actually use it.

  3. You can also "/" restrict information to only the same origin by using it. However, when the text was completed, only opera browser supported it.
  4. Another thing to keep in mind is that when we specify the source, don't bring a slash behind. That is, to use:
    Window.postmessage (' Send message. ', ' http://example.zhangxinxu.com ');

    Instead of:

    Window.postmessage (' Send message. ', ' http://example.zhangxinxu.com/');

Cross-document browser form communication
The demo above is actually done in a document page. In fact, cross-document communication can also be done between different forms.

You can really click here: cross-document communication between different forms demo

In a modern browser, click the Boys or Girls button (for example, click the Boys button), open the new page sub-2 seconds after the corresponding communication information is displayed. Shown below (from Firefox 10):

This example not only shows the communication that the window sees, but also it is important to show that the specific time control form information is sent.

The demo Main Page has a message global variable named, and when clicked on the male button, the variable value becomes " 我是男生,帅气的男生! "; Click the girl button is "I am a girl, beautiful girl!" ”。 The message is sent from the communication message that you received the open page ‘ready‘ .

The code is a little bit longer, and it's not shown here. The main demo page JS code has, and highlighted, there are Chinese comments, I believe it is not difficult to understand.

I would also like to cite a practical example, such as an iframe height adaptation problem. However, one is lazy, and the other is to worry about hiding deep and difficult to find. It's good to be free here. When you have energy, you can talk about it.

As I mentioned at the beginning of this article, IE8 does not support form communication, but careful you may find that there is no effect under IE9 browser. To not other, but seemingly IE9 has not provided e.currentTarget.opener the interface, so that the demo nap.

Iv. Channel Communication

The message channel provides a direct, bidirectional browsing context between the means of communication. As with cross-document communication, the DOM is not exposed directly. Instead, each end of the pipeline is a port, the data is sent from one port, and the other becomes an input (and vice versa).

Message channels are useful, especially across multiple origins of communication. Consider the following scenario: Renren (http://renren.com) embeds a third-party game page (in the form of an IFRAME, such as "everyone's Restaurant"), and this third-party game page (http://game.com) needs to be from another Address book site ( http://address.com) Gets the user's communication information. Do how

That is to say, the Address book site to send information to the game site, according to cross-document communication, we have the parent page as a proxy (that is, everyone here) (similar to the first demo). However, this approach means that the Address book site needs to have the same level of trust as everyone's web page. Renren this social site needs to trust every request, or filter for us (it should mean: a single designation).

However, with channel communication, the Address Book site (http://address.com) and the game site (http://game.com) can communicate directly.

Messagechannel and Messageport objects
When we created an MessageChannel object, we actually created two interrelated ports. One port remains open for the sending side. The other one is forwarded to the other browsing context.

Each port is an MessagePort object that contains 3 available methods:

PostMessage () Sending messages over channels
Start () Start dispatching accepted information on the port
Close () Close port

MessagePortThe object also has an onmessage event property that can be used to define an event handle rather than an event listener.

Instance
Above the terminology of things I myself can not understand, or instance bcause.

You can ruthlessly click here: Channel Communication Application Demo

The article has already been mentioned in the Beginning Compatibility section, the Firefox browser does not currently support the communication channel, so the demo needs to be opened in opera or Chrome browser.

Demo page operation similar to the first demo, left input information, click the button to submit.

For example, under the Opera browser:

Of course, not every time is OK, sometimes pop-up "port is not available prompt", the reason is unknown, it may be related to the port is occupied, encountered this situation, try later.

Brief analysis
The demo above uses three pages: the main page and two iframe pages. Let's talk about what each page does:

First is the first IFRAME page (the one on the left of the demo that has the form submitted). There are two tasks: one is to tell the main page, I load well, and the other is to enlarge and determine the port, which is used for sending when the form is submitted.

Tell the main page, I loaded the window.parent.postMessage (' send page loading complete ', ' http://www.zhangxinxu.com ');
Expand and determine port ports = evt.ports[0];//port to send data port.postmessage (message);

Then the second IFRAME page (the one on the right of the demo to display the information). There are three tasks, one is to create the channel object, the other MessageChannel is to tell the main page, I loaded, and the end of the oral pass; the third is to display the sending message.

Create a new Messagechannel object var mc = new Messagechannel ();//Send a port to the parent window.parent.postMessage (' Show page loading complete ', '/HTTP/ Www.zhangxinxu.com ', [Mc.port1]);
Displays the message sent Mc.port2.addEventListener (' message ', Messagehandle, false); Mc.port2.start ();

Finally, the main page. The task is simple: Tell the first IFRAME page that the port is open (the first IFRAME can identify the port that communicates with the second IFRAME).

Tell the port to other documents Window.frames[0].postmessage (' Port open ', ' http://www.zhangxinxu.com ', evt.ports);

So, the three associated with the match, it is done!

V. Other RESOURCES

There is a Web communication document on the SlideShare, which shows that interested children's shoes can be viewed quickly.

HTML5 Web 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.