“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

The original intention of this series of articles is to “let each front-end engineer master the high frequency knowledge, for the work of power”. This is the front end of the 25th cut, I hope friends pay attention to the public number “kite”, armed with knowledge of their minds.

25.1 Same-origin Policy

25.1.1 homologous

Cross-domain essentially means that two urls have different IP addresses from different sources. The reverse side of different IP addresses is same-origin. Same-origin means that if two urls have the same protocol, domain name, and port number, they are two urls of the same origin.

// Non-same-origin: different protocols http://www.baidu.com https://www.baidu.com // Same-origin: the protocol, domain name, and port number are the same http://www.baidu.com http://www.baidu.com?query=1Copy the code

25.1.2 Same-origin Policy

The same origin policy is an important security policy that restricts how an Origin document or loaded script it loads can interact with resources from another source. It is mainly to protect the security of user information and prevent malicious websites from stealing data. It is the security protection done by the browser at the level of Web pages.

25.1.3 Same-origin Policy

Since the same origin policy is protected by the browser at the Web page level, where on that level should be protected? It mainly includes three levels: DOM level, data level and network level.

  1. The DOM level

The same origin policy restricts how JavaScript scripts from different sources can read and write to the current DOM object.

  1. Data level

The same origin policy restricts the sites from reading cookies, IndexedDB, and localStorage of the current site.

  1. The network layer

The same origin policy restricts the sending of a site’s data to a site of different sources through methods such as XMHttpRequest.

25.2 Cross-domain Classification

The same origin policy ensures the security of the browser. However, if the three levels are strictly restricted, it will make the programmer’s development work difficult. Therefore, the browser needs to make some concessions under the strictest same-origin policy, which is more a trade-off between security and convenience. The cross-domain approach can be thought of as a compromise between the browser giving up some security or complying with the browser’s same-origin policy.

25.2.1 DOM layer and Data Layer Classification

According to the same origin policy, it is common for two pages with different sources to communicate with each other if they cannot manipulate DOM and access data. A typical example is the communication between an IFrame window and its parent window. Over the course of history, there are several ways to implement communication between DOM layers, as follows:

  1. Fragment identifier

The core idea of a fragment identifier is to listen for changes in the HASH in the URL to pass the data, which is a really neat idea.

// The parent page parentHtml<! DOCTYPEhtml>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>I am the parent page<button id='btn'>Father to son</button>
        <iframe src="./childHtml.html" id="childHtmlId"></iframe>
    </body>
    <script>
        window.onhashchange = function() {
            console.log(decodeURIComponent(window.location.hash));
        };
        document.getElementById('btn').addEventListener('click'.() = > {
            const iframeDom = document.getElementById('childHtmlId');
            iframeDom.src += '# father to son ';
        });
    </script>
</html>
Copy the code
// Child pages childhmt.html<! DOCTYPEhtml>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>I'm a child page<button id='btn'>Son to father</button>
    </body>
    <script>
        window.onhashchange = function() {
            console.log(decodeURIComponent(window.location.hash));
        };

        document.getElementById('btn').addEventListener('click'.() = > {
            parent.location.href += '# child to father ';
        });
    </script>
</html>
Copy the code
  1. window.name

The browser window has the window.name attribute. The biggest feature of this attribute is that, regardless of whether the same source, as long as the previous page in the same window set this attribute, the next page can read it. If the communication between the parent page and the cross-domain child page is needed, a child page with the same origin as the parent page is used as an intermediary to transfer the information in the cross-domain child page. (Very troublesome ah, strongly not recommended to use, here will not write the corresponding code)

  1. document.domain

Document.domain is the host name of the server where the document is stored. It can be manually set to the current domain name or the superior domain name. When the same document.domain page is equivalent to being on the server with the same domain name.

  1. PostMessage (highly recommended)

Window. postMessage is a new CROSS-document communication API for HTML5 that allows cross-window communication regardless of whether the two Windows are homologous or not.

/ / the parent page<! DOCTYPEhtml>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>I am the parent page<button id='btn'>Father to son</button>
        <iframe src="http://127.0.0.1:5500/024/childHtml.html" id="childHtmlId"></iframe>
    </body>
    <script>
        window.addEventListener('message'.function(event) {
            console.log('Parent page receives message', event.data);
        });
        document.getElementById('btn').addEventListener('click'.() = > {
            const iframeDom = document.getElementById('childHtmlId');
            iframeDom.contentWindow.postMessage('I am the Kite Bearer 1'.'http://127.0.0.1:5500/024/childHtml1.html');
        });
    </script>
</html>
Copy the code
/ / child pages<! DOCTYPEhtml>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>I'm a child page<button id='btn'>Son to father</button>
    </body>
    <script>
        window.addEventListener('message'.function(event) {
            console.log('Child page receives message', event.data);
        });

        document.getElementById('btn').addEventListener('click'.() = > {
            parent.postMessage('I am the Kite Bearer 2'.'http://127.0.0.1:5500/024/parentHtml1.html');
        });
    </script>
</html>
Copy the code

25.2.2 Network Layer

By default, browsers do not allow XMLHttpRequest objects to access resources on different sites, according to the same origin policy. This can greatly limit productivity, so you need to overcome this restriction and achieve cross-domain access to resources. At present, there are three main methods widely used (note: the specific code is not given in this paper, there will be a special 100 questions cut for detailed elaboration) :

  1. By proxy

The same origin policy is set by the browser for security, so there is no such restriction on the server side. In this way, we can send requests to the same origin server, and then the same origin server proxy to the final required server, thus realizing the purpose of cross-domain request. For example, Nginx, Node middleware, etc.

  1. JSONP method (see the specific implementation of the following hundred questions cut)

JSONP is a technology that uses script elements to achieve cross-domain implementation. It does not use XMLHttpRequest objects. It can achieve cross-domain implementation mainly because script has two characteristics:

(1) The SRC attribute can access any URL resources and is not restricted by the same origin policy;

(2) If the accessed resource contains JavaScript code, it will be automatically executed after downloading.

  1. CORS mode (see the specific implementation of the following 100 questions cut)

Cross-domain resource sharing (CORS), a mechanism that enables cross-domain access control to secure cross-domain data transfer. A way to implement a cross-domain request in which HTML accesses the url http://127.0.0.1:8009; Server listening port: 8010)

(1) HTML page content

<! DOCTYPEhtml>
<html>
    <head>
        <meta charset="UTF-8">
        <title>test CORS</title>
    </head>
    <body>
        CORS
        <script src="https://code.bdstatic.com/npm/[email protected]/dist/axios.min.js"></script>
        <script>
            axios('http://127.0.0.1:8010', {
                method: 'get'
            }).then(console.log)
        </script>
    </body>
</html>
Copy the code

(2) Server-side code

const express = require('express');

const app = express();

app.get('/'.(req, res) = > {
    console.log('Get request received!! ');
    res.setHeader('Access-Control-Allow-Origin'.'http://127.0.0.1:8009');
    res.send('Get request already processed');
})
app.listen(8010.() = > {
    console.log('8010 is listening')});Copy the code

1. If you think this article is good, share and like it so that more people can see it

2. Pay attention to the public number of kite, and the number of the Lord together to kill the front hundred