Home  >  Article  >  Web Front-end  >  What is cross-domain? Introduction to four ways of cross-domain JavaScript

What is cross-domain? Introduction to four ways of cross-domain JavaScript

不言
不言forward
2018-10-22 13:54:1312981browse

This article brings you a detailed explanation of PHP synergy implementation (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is cross-domain

What is cross-domain? Introduction to four ways of cross-domain JavaScript

##JavaScript For security reasons, Cross-domain calls to objects from other pages are not allowed. So what is cross-domain? A simple understanding is that because of the restrictions of the JavaScript same-origin policy, js under the domain name a.com cannot operate objects under the domain name b.com or c.a.com.

When any of the protocol, subdomain name, main domain name, and port number are different, they are all counted as different domains. Requesting resources from different domains is considered "cross-domain".
For example: http://www.abc.com/index.html requests http://www.efg.com/service.php.

One thing must be noted:

Cross-domain does not mean that the request cannot be sent out, the request can be sent out, the server can receive the request and return the result normally, but the result is intercepted by the browser . The reason why it occurs across domains is that it is restricted by the same-origin policy. The same-origin policy requires that the source is the same for normal communication, that is, the protocol, domain name, and port number are all exactly the same.

You can refer to the picture below to help you understand cross-domain in depth.

What is cross-domain? Introduction to four ways of cross-domain JavaScript

Special note on two points:

First: If there are cross-domain problems caused by protocols and ports, the "front desk" is powerless. of.

Second: Regarding cross-domain issues, domains are only identified by the "header of the URL" and will not be judged based on whether the IP addresses corresponding to the domain names are the same. "The header of the URL" can be understood as "the protocol, domain name and port must match".

2. What is the same-origin policy and its restrictions

The same-origin policy restricts how documents or scripts loaded from one source interact with resources from another source. . This is a critical security mechanism for isolating potentially malicious files. Its existence can protect user privacy information, prevent identity forgery, etc. (read Cookie).

The content restricted by the same origin policy includes:

  • Cookie, LocalStorage, IndexedDB and other storage content

  • DOM node

  • AJAX request cannot be sent

But there are three tags that allow cross-domain loading of resources:

1.<img  alt="What is cross-domain? Introduction to four ways of cross-domain JavaScript" >
2.<link>
3.<script></script>
Next, let’s discuss some methods of handling cross-domain. However, all cross-domain transactions must be approved by the information provider. If it can be obtained without permission, there is a vulnerability in the browser's same-origin policy.

3. Cross-domain processing method 1 - JSONP

1.JSONP principle

Utilization<script># With this open policy of the ## element, web pages can obtain JSON data dynamically generated from other sources. JSONP requests must be supported by the other party's server. <code></script>2. Comparison between JSONP and AJAX

JSONP and AJAX are the same. They are both ways in which the client sends a request to the server and obtains data from the server. But AJAX belongs to the same-origin policy, and JSONP belongs to the non-original policy (cross-domain request)

3. JSONP advantages and disadvantages

The advantage of JSONP is that it has good compatibility and can be used to solve cross-origin problems of mainstream browsers. Domain data access issues.

The disadvantage is that only supporting the get method has limitations.

4.JSONP process (take the third-party API address as an example, there is no need to consider the background program)

    Declare a callback function, its function name (such as fn) is used as a parameter value to be passed to the server that requests cross-domain data. The function parameter is to obtain the target data (data returned by the server).
  • Create a
  • <script><p> tag, assign the cross-domain API data interface address to the src of the script, and also request the server in this address Pass the function name (parameters can be passed via question marks:?callback=fn). <code></script>
    • After the server receives the request, it needs to perform special processing: concatenate the passed in function name and the data it needs to give you into a string, for example: passed in The function name is fn, and the data it prepares is fn([{"name":"jianshu"}]).
    Finally, the server returns the prepared data to the client through the HTTP protocol, and the client then calls and executes the previously declared callback function (fn) to operate on the returned data.
  • <script>
        function fn(data) {
            alert(data.msg);
        }
    </script>
    <script></script>
  • where fn is the callback function registered by the client. The purpose is to obtain the json data on the cross-domain server and process the data.
The final format of the data returned by the server to the client is:

fn({ msg:'this  is  json  data'})

5.jQuery’s jsonp format

JSONP is a GET and asynchronous request, and there are no other requests. method and synchronous request, and jQuery will clear the cache for JSONP requests by default.

$.ajax({
url:"http://crossdomain.com/jsonServerResponse",
dataType:"jsonp",
type:"get",//可以省略
jsonpCallback:"fn",//->自定义传递给服务器的函数名,而不是使用jQuery自动生成的,可省略
jsonp:"jsonp",//->把传递函数名的那个形参callback变为jsonp,可省略
success:function (data){
console.log(data);}
});

4. Cross-domain processing method 2 - CORS

1.CORS原理

整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信

2.CORS优缺点

CORS要求浏览器(>IE10)和服务器的同时支持,是跨域的根本解决方法,由浏览器自动完成
优点在于功能更加强大支持各种HTTP Method,缺点是兼容性不如JSONP。
只需要在服务器端做一些小小的改造即可:

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:POST,GET");

例如:网站http://localhost:63342/ 页面要请求http://localhost:3000/users/userlist  页面,userlist页面返回json字符串格{name: 'Mr.Cao', gender: 'male', career: 'IT Education'}

//在服务器端设置同源策略地址
router.get("/userlist", function (req, res, next) {   
    var user = {name: 'Mr.Cao', gender: 'male', career: 'IT Education'};  
    res.writeHeader(200,{"Access-Control-Allow-Origin":'http://localhost:63342'});  
    res.write(JSON.stringify(user));  
    res.end();  
});

在响应头上添加Access-Control-Allow-Origin属性,指定同源策略的地址。同源策略默认地址是网页的本身。只要浏览器检测到响应头带上了CORS,并且允许的源包括了本网站,那么就不会拦截请求响应

What is cross-domain? Introduction to four ways of cross-domain JavaScript

五、处理跨域方法三——WebSocket

Websocket是HTML5的一个持久化的协议,它实现了浏览器与服务器的全双工通信,同时也是跨域的一种解决方案。WebSocket和HTTP都是应用层协议,都基于 TCP 协议。但是 WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。

原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。

//前端代码:
<p>user input:<input></p>
<script></script>
<script>
var socket = io(&#39;http://www.domain2.com:8080&#39;);
// 连接成功处理
socket.on(&#39;connect&#39;, function() {
    // 监听服务端消息
    socket.on(&#39;message&#39;, function(msg) {
        console.log(&#39;data from server: ---> &#39; + msg); 
    });

 // 监听服务端关闭
    socket.on(&#39;disconnect&#39;, function() { 
        console.log(&#39;Server socket has closed.&#39;); 
    });
});
document.getElementsByTagName(&#39;input&#39;)[0].onblur = function() {
    socket.send(this.value);
};
</script>
//Nodejs socket后台:
var http = require('http');
var socket = require('socket.io');
// 启http服务
var server = http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-type': 'text/html'
    });
    res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
// 监听socket连接
socket.listen(server).on('connection', function(client) {
    // 接收信息
    client.on('message', function(msg) {
        client.send('hello:' + msg);
        console.log('data from client: ---> ' + msg);
    });

    // 断开处理
    client.on('disconnect', function() {
        console.log('Client socket has closed.'); 
    });
});

六、处理跨域方法四——postMessage

如果两个网页不同源,就无法拿到对方的DOM。典型的例子是iframe窗口和window.open方法打开的窗口,它们与父窗口无法通信。HTML5为了解决这个问题,引入了一个全新的API:跨文档通信 API(Cross-document messaging)。这个API为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。postMessage方法的第一个参数是具体的信息内容,第二个参数是接收消息的窗口的源(origin),即"协议 + 域名 + 端口"。也可以设为*,表示不限制域名,向所有窗口发送。

接下来我们看个例子:
http://localhost:63342/index.html页面向http://localhost:3000/message.html传递“跨域请求信息”

//发送信息页面 http://localhost:63342/index.html
  
  
    <meta>  
    <title>跨域请求</title>   
  
  
    <iframe></iframe>  
    <input>  
  
  
<script>  
   function  run(){  
        var frm=document.getElementById("frm");  
        frm.contentWindow.postMessage("跨域请求信息","http://localhost:3000");  
   }  
</script>
//接收信息页面 http://localhost:3000/message.html
 window.addEventListener("message",function(e){  //通过监听message事件,可以监听对方发送的消息。
  console.log(e.data);  
},false);

The above is the detailed content of What is cross-domain? Introduction to four ways of cross-domain JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete