HTML5 Communication API
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 is considered as secure, and 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>
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 < http://localhost:8080 > To get property authentication using Doc ument from < http://loverMap.sinaapp.com > It is understood that the source security source is a subset of the addresses where the application establishes 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. The browser supports if (typeof window. postMessage = "undefined") {// the browser does not support postMessage} To send a 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. The message event listening 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 application running of the instance depends on two prerequisites: first, the page must be deployed on the web server; 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. Mainly concentrated in 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 ); } };
The main attribute xhr. readyState that contains XMLHttpRequest: 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 the following 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-origin 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 build web applications based on non-same-Source Services. 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" }
To construct a cross-origin request XMLHttpRequest, you must first create a new XMLHttpRequest object, and then specify different source addresses to construct cross-source XMLHttpRequest: ensure that errors can be monitored during the request process, the request fails due to many reasons, such as network failure, 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 request var xhr = new XMLHttpRequest (); xhr. open ("POST", targetLocation, true); Use the 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 rates.
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 );