search
HomeWeb Front-endJS TutorialWhat is cross-domain? Introduction to four ways of cross-domain JavaScript

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  src="/static/imghwm/default1.png" data-src="http://crossdomain.com/jsonServerResponse?jsonp=fn" class="lazy" 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思否. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)