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