javascript Cross domain Summary of ES1en. name implementation of cross domain data transfer

  • 2020-09-16 07:22:42
  • OfStack

Oneself practice 1, really very useful. The specific implementation method is recorded below

There are 3 pages:

a. com/ app. html: Application page.
a. com/proxy. html: the proxy file, 1 kind is a no html content files, need and application page in the same 1 domain.
b. com/data. html: application need to get the data page, page can be called a data page.

The basic steps are as follows:

In application page (a. com/app. html) created in a iframe, his src pointing to the data page (b. com/data. html).
The data page will attach the data to the ES36en.name of iframe. The code for ES38en.html is as follows:


  <script type="text/javascript">
    window.name = 'I was there!';  //  Here is the data to be transmitted, the size 1 As for the 2M . IE and firefox The bottom can be as big as 32M Or so 
                     //  Data formats can be customized, such as json , string, 
  </script>

In application page (a. com/app. html) listens iframe onload events, set up in this case the iframe src point to the local agent file (proxy files and application page under with 1 domain, so I can communicate with each other). app. html part of the code is as follows:


<script type="text/javascript">
    var state = 0, 
    iframe = document.createElement('iframe'),
    loadfn = function() {
      if (state === 1) {
        var data = iframe.contentWindow.name;  //  Read the data 
        alert(data);  // The pop-up 'I was there!'
      } else if (state === 0) {
        state = 1;
        iframe.contentWindow.location = "http://a.com/proxy.html";  //  Set 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 getting the data, destroy the iframe and free the memory. This also ensures security (not being accessed by other domains, 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 transferred from outdomain to local region, and cross-domain data is transferred from outdomain to local region by ES65en.name of iframe. This neatly circumnavigates the browser's cross-domain access restrictions, but at the same time it is a secure operation.


Related articles: