Resolve cross-domain problems

To understand cross-domain, you must first understand the same-origin policy. The same origin policy is a very important security policy implemented in browsers for security purposes. Same-origin: A URL consists of the protocol, domain name, port, and path. If the protocol, domain name, and port of two urls are the same, they are of the same origin.

1.document.domain

Primary domain name: www.a.com Secondary domain name www.script.a.com

Have the same primary domain, different secondary domain. Add document.domain=’a.com’ to each file;

  • www.a.com/a.html
  • www.script.a.com/b.html

2. Create a script label

Function callback=returnData (){};

  • Accessing the URL returns the accessed information to us in the form of a function call that takes the returned data, which we can use in our custom function

3. The postMessage in HTML 5

The next generation of browsers will support this feature: Chrome 2.0+, Internet Explorer 8.0+, Firefox 3.0+, Opera 9.6+, and Safari 4.0+.

otherWindow.postMessage(message, targetOrigin); OtherWindow: A reference to the window of the receiving page. It can be the contentWindow property of the iframe on the page; The return value of window.open; The value fetched from window.frames by name or subscript. Message: The data to be sent, of type string. TargetOrigin: Used to restrict otherWindow. "*" indicates no restrictionCopy the code
  • The code in a.com/index.html:

    <iframe id="ifr" src="b.com/index.html"></iframe>
    <script type="text/javascript">
    window.onload = function() {
      var ifr = document.getElementById('ifr');
      var targetOrigin = 'http://b.com'; / / if written'http://b.com/c/proxy.html'The effect is the same // if written as'http://c.com'Won't execute postMessage ifr. ContentWindow. PostMessage ('I was there! ', targetOrigin);
    };
    </script>Copy the code
  • The code in b.com/index.html:

    <script type="text/javascript">
      window.addEventListener('message'.function(event){// Determine the message source address using the origin attributeif (event.origin == 'http://a.com') { alert(event.data); / / the pop-up"I was there!"alert(event.source); / / to a.com, the index in the HTML window object reference / / but due to the same origin policy, the event here. The source can not access window object}},false);
    </script>Copy the code

4. Ajax cross-domain instance (front end) :

$.ajax({
        type:,/ / type
        url: ,// Request path
        data:,// The data you want to submit
        dataType: 'jsonp'./ / key
        jsonp: "callback"./ / key
        success: function (data) {
        console.log(data); }});Copy the code