This article brings you a summary (code) of cross-domain solutions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
Same origin policy: the protocol, domain name, and port are all the same.
Non-original restriction:
Cookie, localStorage, and indexDB cannot be read.
DOM cannot be obtained.
The AJAX request cannot be sent.
Solution:
1. JSONP
Principle: Request JSON data from the server by dynamically adding a <script> element. The server receives the request and returns it to the specified named callback function. </script>
eg:
function addScript(src) { var script = document.createElement('script'); script.setAttribute("type", "text/javscript"); script.src = src; document.body.appendChild(script); } window.onload = function() { addScript("https://segmentfault.com/data?callback=getData"); } function getData(data) { console.log(data) }
Note:
1, The callback in the URL of the query needs to specify the name of the callback function.
2. When <script> is run as code in the browser, the defined getData function will be called immediately. <br/>3. The returned JSON parameters are used as JavaScript objects, not strings, and do not require JSON conversion. <br/>4. $.getJSON() of the jquery library can also be implemented. </script>
$.getJSON("https://segmentfault.com/data?callback=?", function(data) { console.log(data) })
Defect: is obtained through GET and does not support POST.
2. window.postMessage
window.postMessage allows cross-window communication regardless of whether it comes from the same source or not. The first parameter of postMessage is to pass the content, and the second parameter is the protocol domain name port or (* means no domain name is restricted)
页面一:"https://www.segmentfault.com/page1.html" //传递页面 <script> window.onload = function () { if (typeof window.postMessage === undefined) { alert("浏览器不支持postMessage!"); } else { window.open.postMessage({data: "Hello World"}, "https://www.example.com/page2.html"); } } </script>
页面二:"https://www.example.com/page2.html" //接收页面 <script> window.addEventListener('message', function(e) { console.log(e.data); },false); </script>
Event reception message in window.addEventListener('message', function(){}); The event object event has three attributes:
1. event.source: the window to send the message
2. event.origin: the URL to which the message is sent
3. event.data: Message content
<script> //引用父窗口发送信息给下一个窗口 window.addEventListener('message', receiveMessage); function receiveMessage(event) { event.source.postMessage('Nice to see you!', '*'); } </script>
<script> //过滤不是发给本窗口的信息 window.addEventListener('message', receiveMessage); function receiveMessage(event) { if (event.origin !== 'http://www.segmentfault.com/page1.html') return; if (event.data === 'Hello World') { event.source.postMessage('Hello', event.origin); } else { console.log(event.data); } } </script>
3. iframe
iframe loading page and the target domain in src are the same domain. It is possible to initiate ajax requests (parent-child window). //The premise is that the source is from the same source. Ajax requests cannot be initiated from different sources.
The window object can be obtained between different windows with the same origin, but the properties and methods of the window object cannot be obtained. //Different sources will report errors
1. document.domain iframe (same source available - cross subdomain)
document.domain attribute: the first-level domain name is the same, but the second-level domain name is different. window object acquisition.
页面一:"https://segmentfault.com/page1.html" <script> window.onload = function() { document.domain = "https://segmentfault.com/"; //设置domain window.getData = function() { //ajax请求 } } </script>
页面二:"https://segmentfault.com/page2.html" <iframe></iframe> <script> //动态创建iframe最佳,获取完数据销毁。 //document.domain设置成自身或更高一级的父域,主域必须相同。 document.domain = "https://segmentfault.com/" //设置domain function test() { var win = document.getElementById("iframe").contentWindow; win.getData("https://segmentfault.com/json_domain.php", function() {}) } </script>
Defect: The primary domain name must be consistent.
2. window.name iframe (available for non-same origin)
window.nameAttributes: During the life cycle of a window, whether it is from the same origin or not , the window.name attribute of the loading page of the same window is shared, and each page can be operated.
页面一:"https://segmentfault.com/page1.html" <script> window.name = "this is data!" </script>
页面二:"https://segmentfault.com/page2.html" <iframe></iframe> <script> //动态创建iframe最佳,获取完数据销毁。 //获取window.name function test() { var winName = document.getElementById("iframe").contentWindow.name; winName.src = "https://segmentfault.com/data.html"; //最后需要将iframe的src设置成当前域的一个页面地址 } </script>
Defects: Poor compatibility
3. location.hash iframe (non-original source available)
Fragment Identifier: The fragment identifier refers to the part after the url# number. Just changing the fragment identifier page does not refresh.
页面一:"https://www.segmentfault.com/page1.html" <script> function startRequest(){ var ifr = document.createElement('iframe'); ifr.style.display = 'none'; ifr.src = 'https://www.example.com/page2.html#messgae'; document.body.appendChild(ifr); } function checkHash() { var data = location.hash ? location.hash.substring(1) : ''; } setInterval(checkHash, 2000); </script>
页面二:"https://www.example.com/page2.html#messgae" <script> function callBack(){ try { parent.location.hash = 'somedata'; } catch (e) { // ie、chrome的安全机制无法修改parent.location.hash, // 所以要利用一个中间的example域下的代理iframe var ifrproxy = document.createElement('iframe'); ifrproxy.style.display = 'none'; ifrproxy.src = 'https:/www.segmentfault.com/page3html#somedata'; // 注意该文件在"segmentfault.com"域下 document.body.appendChild(ifrproxy); } } </script>
页面三:"ttps:/www.segmentfault.com/page3html#somedata" <script> //因为parent.parent和自身属于同一个域,所以可以改变其location.hash的值 parent.parent.location.hash = self.location.hash.substring(1); </script>
Disadvantages: Data is exposed in the URL, and the length is also limited.
4. WebSocket
WebSocket: The browser sends a request to the server to establish a WebSocket connection through JavaScript. After the connection is established, the client and server can connect through TCP Exchange data directly.
Set the WebSocket request header information and the server supports it.
Origin: http://example.com //根据域名是否在白名单内来判断是否可以通信
Disadvantages: High implementation cost.
5. CORS
cors is cross-domain resource sharing. The key to current CORS communication is the server. As long as the server implements the CORS interface, cross-origin communication is possible.
Disadvantages: Server configuration, occupying the bandwidth of the main domain.
This article has ended here. For more exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!
The above is the detailed content of Summary of JavaScript cross-domain solutions (code). For more information, please follow other related articles on the PHP Chinese website!

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version
