当前位置:网站首页>Eight solutions to cross domain problems (the latest and most comprehensive)
Eight solutions to cross domain problems (the latest and most comprehensive)
2022-07-21 19:12:00 【qq_ twenty-five million seven hundred and forty-one thousand an】
from PheonixHkbxoic Of 《 Front end solution to cross domain problems 8 Kind of plan ( The latest and most complete )》
Original address :https://www.cnblogs.com/PheonixHkbxoic/p/5760838.html
1. The same-origin policy as follows :
URL | explain | Whether to allow communication |
---|---|---|
http://www.a.com/a.js | ||
http://www.a.com/b.js | Under the same domain name | allow |
http://www.a.com/lab/a.js | ||
http://www.a.com/script/b.js | Different folders under the same domain name | allow |
http://www.a.com:8000/a.js | ||
http://www.a.com/b.js | The same domain name , Different ports | Don't allow |
http://www.a.com/a.js | ||
https://www.a.com/b.js | The same domain name , Different protocols | Don't allow |
http://www.a.com/a.js | ||
http://70.32.92.74/b.js | Domain names correspond to domain names ip | Don't allow |
http://www.a.com/a.js | ||
http://script.a.com/b.js | Primary domain is the same , Different subdomains | Don't allow |
http://www.a.com/a.js | ||
http://a.com/b.js | The same domain name , Different secondary domains ( ditto ) | Don't allow (cookie Access is also not allowed in this case ) |
http://www.cnblogs.com/a.js | ||
http://www.a.com/b.js | Different domain name | Don't allow |
Pay special attention to two points :
First of all , If the protocol and port cause cross domain problems “ The front desk ” There's nothing we can do ,
second : On cross-domain issues , Domain is only through “URL The first ” To identify and not try to judge the same ip The address corresponds to two domains or whether two domains are in the same ip On .
“URL The first ” finger window.location.protocol +window.location.host, It can also be understood as “Domains, protocols and ports must match”.
2. The front end solves cross domain problems
1> document.domain + iframe ( This method can only be used when the primary domain is the same )
- stay www.a.com/a.html in :
document.domain = 'a.com';var ifr = document.createElement('iframe');ifr.src = 'http://www.script.a.com/b.html';ifr.display = none;document.body.appendChild(ifr);ifr.onload = function(){
var doc = ifr.contentDocument || ifr.contentWindow.document; // Operate here doc, That is to say b.html ifr.onload = null;};
- stay www.script.a.com/b.html in :
document.domain = 'a.com';
2> Dynamically create script
There's nothing to say about this , because script Tags are not restricted by the same origin strategy .
function loadScript(url, func) {
var head = document.head || document.getElementByTagName('head')[0]; var script = document.createElement('script'); script.src = url; script.onload = script.onreadystatechange = function(){
if(!this.readyState || this.readyState=='loaded' || this.readyState=='complete'){
func(); script.onload = script.onreadystatechange = null; } }; head.insertBefore(script, 0);}window.baidu = {
sug: function(data){
console.log(data); }}loadScript('http://suggestion.baidu.com/su?wd=w',function(){
console.log('loaded')});// Where is the content of our request ?// We can do it in chorme Debug panel's source see script Content introduced
3> location.hash + iframe
The principle is to use location.hash To transmit values .
Suppose the domain name a.com The files under the cs1.html Want to be with cnblogs.com Domain name cs2.html Transmit information .
- cs1.html First, automatically create a hidden iframe,iframe Of src Point to cnblogs.com Domain name cs2.html page
- cs2.html After responding to the request, it will be modified cs1.html Of hash Value to pass the data
- At the same time cs1.html Add a timer , Judge at intervals location.hash Is there any change in the value of , Once there is a change, get hash value
notes : Because the two pages are not in the same domain IE、Chrome No modification allowed parent.location.hash Value , So with the help of a.com A proxy under the domain name iframe
The code is as follows :
First, a.com The files under the cs1.html file :
function startRequest(){
var ifr = document.createElement('iframe'); ifr.style.display = 'none'; ifr.src = 'http://www.cnblogs.com/lab/cscript/cs2.html#paramdo'; document.body.appendChild(ifr);} function checkHash() {
try {
var data = location.hash ? location.hash.substring(1) : ''; if (console.log) {
console.log('Now the data is '+data); } } catch(e) {
};}setInterval(checkHash, 2000);
cnblogs.com Domain name cs2.html:
// Simulate a simple parameter processing operation switch(location.hash){ case '#paramdo': callBack(); break; case '#paramset': //do something…… break;} function callBack(){ try { parent.location.hash = 'somedata'; } catch (e) { // ie、chrome The security mechanism of cannot be modified parent.location.hash, // So take advantage of a middle cnblogs Agent under domain iframe var ifrproxy = document.createElement('iframe'); ifrproxy.style.display = 'none'; ifrproxy.src = 'http://a.com/test/cscript/cs3.html#somedata'; // Note that the file is in "a.com" Under domain document.body.appendChild(ifrproxy); }}
a.com Domain name under cs3.html
// because parent.parent Belongs to the same domain as itself , So you can change it location.hash Value parent.parent.location.hash = self.location.hash.substring(1);
4> window.name + iframe
window.name The beauty of :name Values on different pages ( Even different domains ) It still exists after loading , And can support very long name value (2MB).
establish a.com/cs1.html
establish a.com/proxy.html, And add the following code
<head> <script> function proxy(url, func){
var isFirst = true, ifr = document.createElement('iframe'), loadFunc = function(){
if(isFirst){
ifr.contentWindow.location = 'http://a.com/cs1.html'; isFirst = false; }else{
func(ifr.contentWindow.name); ifr.contentWindow.close(); document.body.removeChild(ifr); ifr.src = ''; ifr = null; } }; ifr.src = url; ifr.style.display = 'none'; if(ifr.attachEvent) ifr.attachEvent('onload', loadFunc); else ifr.onload = loadFunc; document.body.appendChild(iframe); }</script></head><body> <script> proxy('http://www.baidu.com/', function(data){
console.log(data); }); </script></body>
3 stay b.com/cs1.html Contained in the :
<script> window.name = ' What to send ';</script>
5> postMessage(HTML5 Medium XMLHttpRequest Level 2 Medium API)
- a.com/index.html The code in :
<iframe id="ifr" src="b.com/index.html"></iframe><script type="text/javascript">window.onload = function() {
var ifr = document.getElementById('ifr'); var targetOrigin = 'http://b.com'; // If written as 'http://b.com/c/proxy.html' The effect is the same // If written as 'http://c.com' They don't execute postMessage 了 ifr.contentWindow.postMessage('I was there!', targetOrigin);};</script>
- b.com/index.html The code in :
<script type="text/javascript"> window.addEventListener('message', function(event){
// adopt origin Property to determine the message source address if (event.origin == 'http://a.com') { alert(event.data); // eject "I was there!" alert(event.source); // Yes a.com、index.html in window References to objects // But due to the homology strategy , here event.source No access window object } }, false);</script>
6> CORS
CORS The idea behind it , It's using custom HTTP The head lets the browser communicate with the server , To determine whether the request or response should succeed , Or should we fail .
IE Chinese vs CORS The implementation of xdr
var xdr = new XDomainRequest();xdr.onload = function(){
console.log(xdr.responseText);}xdr.open('get', 'http://www.baidu.com');......xdr.send(null);
The implementation in other browsers is xhr in
var xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status < 304 || xhr.status == 304){
console.log(xhr.responseText); } }}xhr.open('get', 'http://www.baidu.com');......xhr.send(null);
Implement cross browser CORS
function createCORS(method, url){
var xhr = new XMLHttpRequest(); if('withCredentials' in xhr){
xhr.open(method, url, true); }else if(typeof XDomainRequest != 'undefined'){
var xhr = new XDomainRequest(); xhr.open(method, url); }else{
xhr = null; } return xhr;}var request = createCORS('get', 'http://www.baidu.com');if(request){
request.onload = function(){
...... }; request.send();}
7> JSONP
JSONP It has two parts : Callback functions and data .
The callback function is to place the response on the current page when it arrives Called Function of .
The data is passed into the callback function json data , That is, the parameters of the callback function .
function handleResponse(response){
console.log('The responsed data is: '+response.data);}var script = document.createElement('script');script.src = 'http://www.baidu.com/json/?callback=handleResponse';document.body.insertBefore(script, document.body.firstChild);/*handleResonse({"data": "zhe"})*/// The principle is as follows :// When we go through script Tag request // The background will be based on the corresponding parameters (json,handleResponse)// To generate the corresponding json data (handleResponse({"data": "zhe"}))// The last one returned json data ( Code ) Will be put in the current js Executed in the file // So far, the cross domain communication is completed
jsonp Although it's very simple , But it has the following disadvantages :
1) safety problem ( There may be security risks in the request code )
2) To be sure jsonp Whether the request fails is not easy
8> web sockets
web sockets It's a browser API, Its goal is to provide full duplex on a single persistent connection 、 Two-way communication .( Homology strategy is very important to web sockets Do not apply )
web sockets principle : stay JS Created web socket after , There will be one. HTTP Request sent to browser to initiate connection . After getting the server response , The established connection will use HTTP Upgrade from HTTP The agreement is exchanged for web sockt agreement .
Only in support of web socket The protocol can work normally on the server .
var socket = new WebSockt('ws://www.baidu.com');//http->ws; https->wsssocket.send('hello WebSockt');socket.onmessage = function(event){ var data = event.data;}
边栏推荐
猜你喜欢
Clickhouse architecture
ClickHouse表引擎
V853 development board hardware data - risc-v core e907 user manual
Postgresql源码(64)查询执行——子模块Executor(2)执行前的数据结构和执行过程
红枣科技CEO月度DDC说明会(第三期)——DDC网络新功能介绍及文昌链升级计划 精华回顾
Unity—Input类
不想醒来因为好吃
FTP服务配置
SuperMap iClient for OpenLayers图层组控制实现方法
JMeter learning notes 003-csv parameterization of JMeter
随机推荐
MYSQL07_获取日期函数、聚合函数、字符串函数
Unity - input class
Leetcode - prefix sum and difference
FTP服务配置
【云原生之kubernetes】kubernetes集群下的健康检查使用方法
TCP protocol
Manual implementation of solving single source shortest path
Alibaba cloud released the industry's first "best practice map of live video technology"!
Ardunio development - use of soil sensors
The new red envelope cover platform can build the source code of the independent background of the sub station
JMeter学习笔记003-JMeter之CSV参数化
Don't be silly to distinguish these kinds of storage volumes of kubernetes
论文翻译解读:Anytime Bottom-Up Rule Learning for Knowledge Graph Completion【AnyBURL】
[QT] correct method of character encoding conversion of log path
Ardunio开发——I2C协议通讯——控制2x16LCD
toast_tuple_threshold的疑问
Essential tools for streamlit Data Science
synchronized锁范围
regular expression
[experience sharing] mathematical modeling paper format requirements and summary of common problems