I’ve looked at cross-domains before, but it’s all on the surface, and it feels awkward. So I want to pick up a variety of cross-domain principles, so that their understanding is more profound.

Understanding the Same Origin Policy

After studying these days, I came up with an understanding of cross-domain: cross-domain is a supplement to the same-origin policy, which makes the same-origin policy more flexible. So I want to talk about the concept of same-origin policy first.

For security, all browsers support the same origin policy, which has the following functions:

Disallow two unrelated sites from accessing each other’s cookies

It would be really scary if there were no restrictions, see the following scenario:

  1. A wants to transfer money through online banking. After successful login, the server will store A token in the cookie of Bank.com under the browser.
  2. In the future, every time you access the online bank, you will pass the token to the server. If the server passes the verification, the login is successful.
  3. At this time, B sent an indescribable website xxx.com to A, and A excitedly opened the website quickly
  4. But unexpectedly, XXX website secretly called the bank’s transfer interface and transferred 1 yuan to an overseas account.

Normal transfer interface will do token verification, but in the case just now, because there is no same-origin policy, xxx.com can easily obtain the token under Bank.com, so that the transfer can be successful.

The websites in domain A are prohibited from accessing the resources in domain B

In fact, the above chestnut has a premise, that is, XXX website can access the Bank transfer interface, and this premise is also managed by the same origin policy.

Disallow Dom queries with websites and iframes

If this is open, it’s bad. See the following scenario:

  1. You wake up to an email notifying you of an unusual credit card charge and asking you to click on a website provided in the emailbanik.com(Real websitebank.com) Website enquiries
  2. You follow his leadbanik.comAfter logging in to check, it turns out to be a false alarm, and there is no abnormal consumption, and then happily go to work
  3. In the evening, a text message prompts you to make a large transfer, so log onbank.comI checked and found that the money had actually been transferred. 😿 😿 😿 😿

Banik.com is a phishing site provided by scam emails. The site is relatively simple and has two parts:

  1. A full-screen IFrame tag and load the real official websitebank.com
  2. A script to get the iframe account password input box node

Without the same origin policy, Banik.com can access the BANK.com DOM node and then get the account password you entered easily.

Understand the cross-domain

I mentioned my understanding of cross-domain: Cross-domain is a supplement to the same-origin policy, making it more flexible. Now let’s talk a little bit about the cross-domain additions to the same origin policy. (Please leave comments if you have other ideas)

On the basis of security, domain A websites can access domain B resources

Here’s a q&A to break this down.

  1. Why do domain A websites access domain B resources

    1. For small sites, it is no problem to put js, CSS, images and other resources on the same server, but when the size of the site is getting bigger and bigger, the number of users is increasing, the pressure on the server will double, thus affecting the response efficiency of the server. Therefore, we need to place resources on different servers, creating cross-domain requirements.

    2. With the flourishing development of the front end, many excellent third-party services have evolved, and these third-party services must be inconsistent with the company’s domain name, so there is also cross-domain demand

  2. What are the official cross-domain methods

    1. Early on, officials were aware of the first problem, and so letscript,imgTags are cross-domain supported
    2. Later, for the second problem, we launched a W3C standard: CORS(Cross-origin Resource Sharing), which will be explained in detail
  3. What are the unofficial cross-domains

    Refers to the use of some strange techniques to achieve cross-domain, there are three main types

    1. JSONP – Based script tags support only GET requests, which can fetch the server’s response data
    2. Img – Based on the IMG tag, only GET requests are supported and the response data from the server cannot be obtained
    3. Iframe – Based on the IFrame tag support various request methods, cannot obtain the server response data

On the basis of ensuring security, websites in domain A can access cookies in domain B

In the same origin policy, this kind of behavior is explicitly prohibited, but there are policies at the top and countermeasures at the bottom, which can be realized by using the curve to save the country. Various advertising alliances are done in this way, refer to the following scenarios:

  1. I have a website, Juzi.com, which has a daily page view of one million. I want to access JD’s advertising alliance to make some extra money. After various procedures, I got the following code and embedded it into the advertising module of my website (you can also directly access the following iframe specified link in the browser, and the effect is the same).

    <iframe scrolling="no" frameborder="0" src="http://x.jd.com/exsites?spread_type=2&ad_ids=137:5&unid=1&callback=getjjsku_callback" marginwidth="0" marginheight="0" style="width:300px; height:250px;"></iframe>
    Copy the code
  2. After the release, I want to see the effect. So I went to jingdong’s official website to search for two keywords: stroller and iphone6, and then refreshed my website, and found that the advertising module began to push the products of stroller and iphone6 to me.

In this chestnut, the most magical point is how a website that has nothing to do with JINGdong knows what you have visited in jingdong. Here we go:

  1. First of all, IN addition to jingdong provided me with the advertising code, injuzi.comThere is no direct or indirect interaction with JINGdong on the website.
  2. The key is that JINGdong gave me the code, an iframe tag and specified its SRC to point to jingdong’s secondary domain name, becauseIframe supports cookie access between subdomain names and root domain namesTherefore, iframe in orange will bring the cookie you just left when visiting the official website of JINGdong when making a request to Jingdong, so Ijuz.comJingdong alliance advertising can know the content you want.
  3. What iframe is for, I won’t bother here.

Cross-domain practice

In this article, I will only mention the first scenario: make domain A sites accessible to domain B resources on the basis of security, and the second scenario, through the advertising alliance chestnut can know how to do so, I won’t go into too much description.

Let’s do it one by one in the order in which cross-domain approaches appear

Label cross-domain

To ease server stress, the W3C standard allows script and IMG tags to operate across domains, so we can put interface requests directly into these tags, and create them dynamically for more flexibility

advantage

No back-end coordination is required

disadvantage

  1. Only GET requests are supported
  2. Could not get response data

practice

function addTrack(params) {
   const trackTag = document.createElement('script');
   // Use the QS library to serialize objects
   trackTag.src = `wwww.addTrack.com?${Qs.stringify(params)}`;
   // If the img tag is used, it is recommended to add this sentence to avoid affecting the user experience
   trackTag.display = 'none';
   document.body.appendChild(trackTag);
}
addTrack({ page: 'home' });
Copy the code

The json cross-domain

JSON with Padding, which is based on script tags

advantage

You can get the data for the response

disadvantage

  1. Only supports the get
  2. Backend coordination is required

Realize the principle of

The front end

function getRequest(data) {
   const script = document.createElement('script')
   // 1. The main function is to get the response of the request
   window.jsonpCb = (res) = > {
     document.body.removeChild(script)
     delete window.jsonpCb
   }
    // 2. Use the CB field to tell the front-end server that the function used to receive the response is jsonpCb
   script.src = `www.juzi.com?${Qs.stringify(data)}&cb=jsonpCb`
   document.body.appendChild(script)
}
Copy the code

The back-end

router.get('/get'.function(req, res, next) {
  // 1. Get the function passed by the front end
  var _callback = req.query.cb;
  var responseData = { email: '[email protected]'.name: 'GG' };
  // 2. Check whether the CB field exists. If no CB field exists, a message is displayed
  if (_callback){
      // 3. Set the data type of the returned data, specifying js code here
      res.type('text/javascript');
      // 4. Spell jsonpCb({email: '[email protected]', name: 'GG'}) and respond
      res.send(_callback + '(' + JSON.stringify(responseData) + ') ');
  } else {
    res.send('Did not get callback function'); }});Copy the code

When I first started working with JSONP, I was completely confused by the code. To understand the above code, we need to understand how the script tag works. For example, if I want to introduce the jQuery library, we just need to write like this to use the jQuery function

<script type='text/javascript' src='www.jQuery.com'></script>
Copy the code

But what the browser is really doing is putting the contents of the www.jQuery.com response into the script tag, which means that the code above becomes the following code

<script type='text/javascript'>
 / / the jQuery source code
</script>
Copy the code

JSONP: JSONP: JSONP: JSONP: JSONP: JSONP: JSONP

<script type='text/javascript' src='www.juzi.com?name=GG&cb=jsonpCb'></script>
Copy the code

The actual operations of the browser are as follows:

<script type='text/javascript'>
    // The following code is the content of the interface response, so you should know that this is where the front-end setup callback is executed
	jsonpCb({ email: '[email protected]', name: 'GG' })
</script>
Copy the code

The iframe cross-domain

There are two types of iframe across domains, the second of which is described in this section

  1. Get cookies across domains like AD consortia,
  2. Send a cross-domain request

advantage

This method can only be used with the Form component, so any request method supported by from is supported here

disadvantage

Because the DOM query between the same-origin policy banned across the window, under normal circumstances this way only can know whether the request is successful, but unable to get the request data, but the net friend of infinite wisdom, come up with the following three chi Yin techniques to achieve cross-domain window before communication, respectively is: the fragment identifier/window name/communication API across documents. Here do not do too much explanation, interested friends can try.

Realize the principle of

The underlying principle is the same as advertising alliance, but in a different way.

const requestPost = ({url, data}) = > {
  const iframe = document.createElement('iframe')
  iframe.name = 'iframePost'
  iframe.style.display = 'none'
  document.body.appendChild(iframe)
  const form = document.createElement('form')
  const node = document.createElement('input')
  // Iframe is loaded only when the excuse access is successful, so we can use this mechanism to determine whether the interface access is successful
  iframe.addEventListener('load'.function () {
    console.log('post success')
  })

  form.action = url
  form.target = iframe.name
  form.method = 'post'
  for (let name in data) {
    node.name = name
    node.value = data[name].toString()
    form.appendChild(node.cloneNode())
  }
  // Form elements need to be added to the main document.
  form.style.display = 'none'
  document.body.appendChild(form)
  form.submit()

  // After the form is submitted, the form can be deleted without affecting the next data delivery.
  document.body.removeChild(form)
}
// The usage mode
requestPost({
  url: 'http://localhost:9871/api/iframePost'.data: {
    msg: 'helloIframePost'}})Copy the code

There are two prerequisites for an appeal code to be read:

  1. Understand the operation mechanism of advertising alliance
  2. Understand iframe and form tags, especially what the target attribute of the form tag does

CROS cross-domain

CROS stands for Cross-Origin Resource Sharing. If you want to know more about it, please go to see Ruan Yifeng’s CROSS-domain resource sharing CORS. Below, I will record the questions I met in the process of learning CROS through the way of question and answer.

  1. Whose function is Cros, the network library?

    CORS is a W3C standard that every browser follows

  2. Who made the pre-check request?

    The client sends a request, and the browser intercepts it to determine if it is a cross-domain request, and if so, sends an Opitons request to the server

  3. Who is responding to precheck requests?

    It’s our own server

  4. The Origin field in the precheck request is automatically displayed by the browser, so you don’t have to write it yourself

  5. How to send data to the client when the backend does not write the interface related to the options request?

    After checking a lot of information, I failed to find it. At present, it is understood as follows: as long as the server supports options request, the following response header will be returned automatically, without special intervention

    1. Access-Control-Allow-Origin
    2. Access-Control-Allow-Headers
    3. Access-Control-Allow-Methods
  6. What does the back end need to do

    1. Support for Options requests
    2. Where options requests are supported, set the following fields according to your situation:
      1. Access-Control-Allow-Origin
      2. Access-Control-Allow-Headers
      3. Access-Control-Allow-Methods
      4. Access-Control-Allow-Credentials
  7. Precheck the response flow of the request