Web Front-end
JS Tutorial
What is cross-domain? Introduction to four ways of cross-domain JavaScriptWhat 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

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.
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.
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 principleUtilization<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>
-
<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.
- 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"}]).
fn({ msg:'this is json data'})
5.jQuery’s jsonp formatJSONP 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);}
});
整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。 CORS要求浏览器(>IE10)和服务器的同时支持,是跨域的根本解决方法,由浏览器自动完成。 例如:网站http://localhost:63342/ 页面要请求http://localhost:3000/users/userlist 页面,userlist页面返回json字符串格{name: 'Mr.Cao', gender: 'male', career: 'IT Education'} 在响应头上添加Access-Control-Allow-Origin属性,指定同源策略的地址。同源策略默认地址是网页的本身。只要浏览器检测到响应头带上了CORS,并且允许的源包括了本网站,那么就不会拦截请求响应。 五、处理跨域方法三——WebSocket Websocket是HTML5的一个持久化的协议,它实现了浏览器与服务器的全双工通信,同时也是跨域的一种解决方案。WebSocket和HTTP都是应用层协议,都基于 TCP 协议。但是 WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。 原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。 六、处理跨域方法四——postMessage 如果两个网页不同源,就无法拿到对方的DOM。典型的例子是iframe窗口和window.open方法打开的窗口,它们与父窗口无法通信。HTML5为了解决这个问题,引入了一个全新的API:跨文档通信 API(Cross-document messaging)。这个API为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。postMessage方法的第一个参数是具体的信息内容,第二个参数是接收消息的窗口的源(origin),即"协议 + 域名 + 端口"。也可以设为*,表示不限制域名,向所有窗口发送。 接下来我们看个例子:1.CORS原理
2.CORS优缺点
优点在于功能更加强大支持各种HTTP Method,缺点是兼容性不如JSONP。
只需要在服务器端做一些小小的改造即可:header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:POST,GET");
//在服务器端设置同源策略地址
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();
});

//前端代码:
<p>user input:<input></p>
<script></script>
<script>
var socket = io('http://www.domain2.com:8080');
// 连接成功处理
socket.on('connect', function() {
// 监听服务端消息
socket.on('message', function(msg) {
console.log('data from server: ---> ' + msg);
});
// 监听服务端关闭
socket.on('disconnect', function() {
console.log('Server socket has closed.');
});
});
document.getElementsByTagName('input')[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.');
});
});
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!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding 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 UseApr 16, 2025 am 12:12 AMPython 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 ResourcesApr 15, 2025 am 12:16 AMPython 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 WorksApr 14, 2025 am 12:05 AMThe 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 ImplementationsApr 13, 2025 am 12:05 AMDifferent 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 WorldApr 12, 2025 am 12:06 AMJavaScript'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)Apr 11, 2025 am 08:23 AMI 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)Apr 11, 2025 am 08:22 AMThis 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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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
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
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)






