HTML5 Communication API, html5communication

Source: Internet
Author: User

HTML5 Communication API, html5communication

This article discusses two important modules used to build real-time cross-origin communication:Cross-document message communication and XMLHttpRequest Level 2. Through them, we can build compelling Web applications, as a new communication means for HTML5 applications. These two building blocks allow secure communication between web applications in different domains.

 

Cross-document Message Communication

In terms of security, communication between frames, tabs, and Windows running in the same browser has been strictly restricted. For example, sharing information within the browser may be more convenient for some sites, but it also increases the possibility of malicious attacks. If the Browser allows the program to access the content loaded to other frameworks and labels, some websites can use scripts to steal some information from other websites. Browser vendors reasonably restrict such access. when attempting to detect or modify content loaded from other sources, the browser throws a security exception and organizes relevant operations.

However, in practice, there are some reasonable requirements for the content of different sites to interact in the browser. If the browser provides a direct communication mechanism, it can better organize these applications: cross-document message communication.

 

Cross-document message communication ensures secure cross-source communication between iframe, tabs, and windows. PostMessage is a common function in Windows API (application interface). It is used to put a message into a message queue. This method can be used to listen to the message event bound to the window to send cross-document message transmission content.

 

Embed the child page in the parent page through iframe, and call the postMessage method in JavaScript code to send data to the Child Window.

Embed a child page in the parent page and call the postMessage method to send data
<Html> 

Listen to the onmessage event in the subwindow and use JavaScript to display the data sent from the parent window.

The Child Window listens to the onmessage event and displays the data sent from the parent window.
<Html> 

Demo address: http://lovermap.sinaapp.com/test/parent.html

 

Before postMessage, iframe communication is sometimes implemented by writing scripts directly. Execute the script on one page to try to manipulate another file. This method may be in hexadecimal format due to security restrictions. Therefore, postMessage replaces direct programming access and provides an asynchronous communication mechanism in the javascript environment.

If there is no postMessage, cross-source communication will cause security errors. To prevent cross-site scripting attacks, the browser will force such security restrictions.

Error:Permission denied for 

 

Understanding source security

The source is a subset of the addresses that are used to establish trust relationships on the network. The source consists of scheme, host, and port.

Html5 defines source serialization. The source occurs in the form of strings in APIs and protocols. It is very important to use XMLHttpRequest for cross-origin HTTP requests, as is WebSocket.

When processing cross-source communication messages, you must verify the source of each message. In addition, be cautious when processing data with the same message. Even if the message comes from a trusted source, it should be as careful as it is when dealing with external input.

Element. innerHTML = e. data is dangerous because e. data is regarded as a tag, while element. textContent = e. data is relatively safe. We recommend that you do not use a third-party string to evaluate the value. In addition, you can use the window. JSON or json.org parser to avoid using the eval method to process strings inside the application.

 

Browser support

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

Send message

window.postMessage(  document.getElementById("message").value, "http://loverMap.sinaapp.com"); 

This method uses two parameters: the first parameter is the message text sent, but it can also be any JavaScript Object (converted to text through JSON ), the second parameter is the URL address of the message receiving Object window. You can use the wildcard '*' in the URL string to specify all locations. The method uses two parameters: the first parameter is the message text sent, but it can also be any JavaScript Object (converted to text through JSON ), the second parameter is the URL address of the message receiving Object window. You can use the wildcard '*' in the URL string to specify all locations.

Listen to message events

The script can accept information by listening to events in the window object.

window.addEventListener("message", function( event ) {    document.getElementById("content").innerHTML+=event.data+"<br/>";  }, false ); 

 

The running of an instance's application depends on two prerequisites: first, the page needs to be deployed on the web server, and second, the two pages must come from different domains. If you can access multiple web servers in different domains, After deploying the instance file to the server, the instance can run smoothly.

 

XMLHttpRequest Level 2

XMLHttpRequest API makes it possible to implement AJAX technology. As an optimized version of XMLHttpRequest, XMLHttpRequest Level 2 has greatly improved its functionality. The main focus is on two aspects:

1) Cross-origin XMLHttpRequest

2) Progress events.

Traditional XMLHttpRequest

var xhr = new XMLHttpRequest();xhr.open('GET', 'example.php');xhr.send();    xhr.onreadystatechange = function(){    if ( xhr.readyState == 4 && xhr.status == 200 ) {      console.info( xhr.responseText );    } else {      console.info(xhr.statusText );    }  };

Contains the main attributes of XMLHttpRequest

Xhr. readyState: the status of the xhr object. If it is 4, the data is accepted.

Xhr. status: the status code returned by the server. If it is 200, everything is normal.

Xhr. responseText: xml format data returned by the server.

Xhr. statusText: Status text returned by the server.

However, traditional XMLHttpRequest has some disadvantages.

1) it only supports the transmission of text data and cannot be used to read or upload binary files.

2) When transmitting and receiving data, there is no progress information and you can only prompt whether the progress is complete.

3) subject to same-origin restrictions, data can only be requested from servers with the same domain name.

 

 

Cross-origin XMLHttpRequest

In the past, XMLHttpRequest was limited to same-source communication. XMLHttpRequest Level 2 implements XMLHttpRequests through CORS (cross-source resource sharing. Because the path may contain sensitive information, the browser may not necessarily send Referer to protect user privacy, and the browser will send the Origin header whenever necessary.

Cross-source XMLHttpRequest can be used to buildNon-same sourceThe web application of the service.

Cross-source XMLHttpRequest can integrate content from different sources from the client. If the target server permits, you can use the user certificate to access protected content, allowing users to directly access personal data. Otherwise, if the same source is not integrated on the server side, all content must pass through the basic layer on the server side, which may cause a bottleneck.

In fact, the new XMLHttpRequest not only requests data under different domain names (cross-origin requests), but also makes the following progress:

1) You can set the HTTP request time limit.

2) You can use the FormData object to manage form data.

3) You can upload files.

 

4) obtain the binary data of the server.

5) You can obtain the data transmission progress information.

 

Browser support Detection

var xhr = new XMLHttpRequest();if(typeof xhr.withCredentials === undefined){     document.getElementById("support").innerHTML = "you brower does not support"}else{     document.getElementById("support").innerHTML = "you brower support" }

Build a cross-origin request

XMLHttpRequest: first, create a new XMLHttpRequest object,

Next, you can specify different source addresses to construct cross-source XMLHttpRequest:

During the request process, ensure that errors can be monitored. The request fails for many reasons, such as network faults, access rejection, and a lack of CORS support for the target server.

A common way to obtain data from other sources is to use JSONP and use JSONP to design and create a script tag, which contains a URL pointing to a JSON resource. The URL contains the name of the function to be called when the script is loaded. A remote server is responsible for packaging JSON data and calling the name function. This method poses a major security risk. When using JSONP, you must fully trust the data provided by the server, and malicious scripts can take over your applications.

Build cross-source requests

 

var xhr = new XMLHttpRequest();xhr.open("POST", targetLocation, true);

 

Use progress time

Function () {xhr. upload. onprogress = function (e) {var ratio = e. loaded/e. total; setProgress (ratio + "% uploading ");}
Set the callback function to process the progress time, and calculate the upload and download completion rate xhr. onprogress = function (e) {var ratio = e. loaded/e. total; setProgress (ratio + "% loading");} xhr. onload = function (e) {setProgress ("uploaded");} xhr. onerror = function (e) {setProgress ("error");} xhr. open ("POST", targetLocation, true); geoDataString = dataElement. textContent; xhr. send (geoDataString) ;}, true );

Demo address: http://lovermap.sinaapp.com/test/crossOriginUpload.html

 

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.