Cross-domain critical knowledge

  • The same-origin policy

    The browser deliberately designed a feature limitation

  • CORS

    One way to break through browser limitations

  • JSONP

    Compromises in the Internet Explorer era

Definition of homology

  • The source

    Window. origin or location.origin can be the current source

    Source = Protocol + domain name + port number

  • If the protocol, domain name, and port number of two urls are identical, they are the same

  • For example,

    Baidu.com, www.baidu.com different sources

Definition of the same-origin policy

  • The browser defines that if the JS is running in source A, it can only obtain data from source A, not source B. That is, pages from different sources are not allowed to access each other’s data.
  • Purpose: To protect user privacy

CORS cross-domain method

Example: 1. Create qq-com with server.js in it to simulate qzone

2. Create hudo-com with server.js to simulate hacker sites

Qq-com contains index.html,qq.js(JS script file), friends.json simulated friend data, port listening 8888

Hubi-com contains index.html, hubi.js (JS script files), and port listener 9999

Normally, you can access json data by running JS in qq.com: 8888, but not by running JS in huo.com:9999, because the browser requires CORS

  • Just add access-Control-allow-origin: URL to the header of the response

The json cross-domain

JSONP is not supported by CORS, but by JSONP. JSONP is not supported by JSON.

Cross-domain steps (implemented via JS)

  • Write the data to frinends.js with a placeholder (functional form)

    And then in the background, you get the JS content, you get the data, you fill that data into the JS, and you send it back to the browser

  • Reference its js at huo.com via the defined window. XXX function,

conclusion

When we cross domains, we have to cross domains in this way because the current browser does not support CORS, or for some reason does not support CORS. The callback name is a random number that we can pass to the background as a callback argument, and the background will return the function to us and execute it.

advantages

Compatible with IE; You can cross domain

disadvantages

Script tag, can’t get what the status code is and header; Does not support the post