Cross-Origin data transmission implemented by window. name in javascript cross-origin summary,
It's really easy to use. The specific implementation method is recorded as follows:
There are three pages:
A.com/app.html:application page.
A.com/proxy.html:the proxy file is generally an HTML file without any content, and its contents and application pages are in the same domain.
B .com/data.html:the page where data is obtained from the application page, which can be called the data page.
The basic steps are as follows:
Create an iframe in the application page (a.com/app.html) and point its src to the data page (B .com/data.html ).
The data page will append the data to the temporary nameof the iframe. the data.html code is as follows:
<Script type = "text/javascript"> window. name = 'I was there! '; // Here is the data to be transmitted. The size is generally 2 MB. The size of IE and firefox can be about 32 MB. // the data format can be customized, such as json and string </script>
Listen to the iframe onload event on the application page (a.com/app.html). In this event, set the src of the iframe to point to the proxy file of the local region (the proxy file and the application page are in the same domain, so they can communicate with each other ). Some codes of app.html are as follows:
<Script type = "text/javascript"> var state = 0, iframe = document. createElement ('iframe'), loadfn = function () {if (state = 1) {var data = iframe. contentWindow. name; // read data alert (data); // The 'I was there! '} Else if (state = 0) {state = 1; iframe. contentWindow. location = "http://a.com/proxy.html"; // sets the proxy file}; iframe. src = 'HTTP: // B .com/data.html'; if (iframe. attachEvent) {iframe. attachEvent ('onload', loadfn);} else {iframe. onload = loadfn;} document. body. appendChild (iframe); </script>
After obtaining the data, destroy the iframe and release the memory. This ensures security (not accessed by other domain frame js ).
<script type="text/javascript"> iframe.contentWindow.document.write(''); iframe.contentWindow.close(); document.body.removeChild(iframe); </script>
To sum up, the src attribute of iframe is changed from external domain to local region, and cross-domain data is transferred from external domain to local region by window. name of iframe. This cleverly bypasses the cross-origin access restriction of the browser, but it is also a secure operation.