HTML5 programming journey Series 2: Discussion on Communication Technology

Source: Internet
Author: User

1. Cross-document Message Communication

For the sake of security, communication between frames, tabs, and Windows running in the same browser has been severely restricted. However, in reality, there are still some reasonable requirements for the content of different sites to interact in the browser. Mashup is a typical example. It is a combination of different applications. To meet the above requirements, a new function is introduced: Cross-document message communication. It ensures secure cross-source communication between iframe, tabs, and windows.

The postMessage API is used to send messages. The sample code is as follows:

chatFrame.contentWindow.postMessage(content,url);

When receiving a message, you must add an event processing function on the page. When the message arrives, you can check the message source to determine how to process the message. The sample code is as follows:

Window. addEventListener ("message", messageHandler, true); function messageHandler (e) {switch (e. origin) {// indicates the data sending source case "friend.example.com": // process the message processMessage (e. data); // the break of the message actually sent by the sender; default: // other message sources // The message is ignored. }}

The postMessage API provides an interactive mode for communication between iframe of different sources.

HTML5 clarifies and improves domain security by introducing source concepts. The source is a subset of the addresses used to establish trust relationships on the network. The source consists of rules (scheme), host (host), and port (port). For example, the source is different because scheme (https, http) is different.

Cross-source communication determines the sender through the source, so that the receiver can ignore or reject messages from non-source sources. At the same time, you need to add listening events to receive messages to avoid being disturbed by information of untrusted applications. However, when using external messages, even reliable data sources should also be cautious to prevent content injection.

To use the postMessage API, follow these steps:

1. Check whether the browser supports

If (typeof window. postMessage === undefined) {// the browser does not support postMessage}

2. Send messages

window.postMessage("Hello","xx.example.com");

The first parameter contains the data to be sent, and the second parameter indicates the destination of the message.

If you want to send a message to iframe, use the following code:

document.getElementById("iframe")[0].contentWindow.postMessage("Hello","xx.example.com");

3. Listen to message events

Window. addEventListener ("message", messageHandler, true); var originWhiteList = ["a.example.com", "B .example.com", "c.example.com"]; function messageHandler (e) {if (checkWhiteList (e. origin) {processMessage (e. data); // The message actually sent by the sender} else {// ignore the sent message} function checkWhiteList (origin) {for (var I = 0; I <originWhiteList. length; I ++) {if (origin = originWhiteList [I]) {return true ;}} return false ;}
Ii. XMLHttpRequestLevel2

XMLHttpRequestLevel2 is an improved version of XMLHttpRequest. It mainly involves cross-source XMLHttpRequess and Progress events (Progress events ).

XMLHttpRequest is only applicable to same-source communication. XMLHttpRequestLevel2 implements Cross-source XMLHttpRequests through Cross-Origin Resource Sharing.

In XMLHttpRequest, The readystatechange event is used to respond to the progress, but it is not compatible in Some browsers. XMLHttpRequestLevel2 uses a meaningful name Progress to name a Progress event. The progress events include loadstart, progress, abort, error, load, and loadend. You can monitor these events by setting callback functions for program properties.

Follow these steps when using XMLHttpRequestLevel2:

1. Check whether the browser supports

Var xhr = new XMLHttpRequest (); if (typeof xhr. withXredentials === undefined) {// the browser does not support XMLHttpRequest}

2. build cross-source requests

var crossOriginRequest = new XMLHttpRequest();crossOriginRequest.open("GET","http://www.example.com",true);

  

During the request process, ensure that errors are monitored to identify the cause of the error and solve the problem.

3. Use progress events

CrossOriginRequest. onprogress = function (e) {var total = e. total; var loaded = e. loaded; if (e. lengthComputable) {// handle other things} crossOriginRequest. upload .. onprogress = function (e) {var total = e. total; var loaded = e. loaded; if (e. lengthComputable) {// handle other things }}
3. postMessage API example application

The cross-source chat application is used as an example to demonstrate the interaction between the portal page and chat components.

Create a postmessageportal.html page in 1 、

<! DOCTYPE html> 

  

Create postmessagewidget.html

<! DOCTYPE html> 

Note: first, the two pages must be deployed on the web server. Second, the two pages must come from different domains. If you want to deploy on the local machine, you need to change the hosts file and add:

127.0.0.1 portal.example.com127.0.0.1 chat.example.net

After the modification, you need to close the browser and open it again.

4. XMLHttpRequestLevel2 example application

1 create crossoriginupload.html page:

<! DOCTYPE html> 

Note: When deploying webapplications and running the crossoriginupload.html page, the following error may occur:

 

This is because the domain used to access a page is not the same as the requested domain. The browser determines whether the domain can be received from the same origin based on the Response Header rules.

So we need http://geodata.example.net: 8080/upload to set Header Access-Control-Allow-Origin, namely:

Response. AddHeader ("Access-Control-Allow-Origin ","*");

When the browser receives the information returned by the server, it checks the Access-Control-Allow-Origin in the response header and Its Value identifies the allowed domain of the request content. If you set Access-Control-Allow-Origin to * on the server, the returned information allows Access from all sources. If it is set to a specific domain, such as a http://xx.com, it indicates that only access from the domain from xx.com is allowed except for the same source.

Link: http://www.cnblogs.com/oooweb/p/html5-communication.html

Via oschina

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.