javascript跨域的几种方法

本文总结了前端开发中解决跨域问题的多种方法,包括动态创建script、document.domain + iframe、location.hash + iframe、window.name + iframe、postMessage、JSONP、CORS以及Web Sockets。详细介绍了每种方法的原理和应用场景,帮助开发者应对不同场景下的跨域挑战。
摘要由CSDN通过智能技术生成

前端开发之跨域方法总结

欲说跨域,首先我们要搞懂同源策略

同源策略:是一种安全策略,为了防止两个不同源的网站之间直接访问数据。

跨域示意图

第一,如果是协议和端口造成的跨域问题“前台”是无能为力的,
第二:在跨域问题上,域仅仅是通过“URL的首部”来识别而不会去尝试判断相同的ip地址对应着两个域或两个域是否在同一个ip上。

“URL的首部”指window.location.protocol + window.location.host,也可以理解为“Domains, protocols and ports must match”。

跨域方法

1、动态创建script

因为script标签不受同源策略的限制。

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')});
//我们请求的内容在哪里?
//我们可以在chorme调试面板的source中看到script引入的内容

2、document.domain + iframe (只有在主域相同的时候才能使用该方法)

浏览器的同源策略使得不同域的框架是不能进行JS的交互操作的。
http://www.a.com/a.html中:

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;
 //在这里操作doc,也就是b.html
 ifr.onload = null;
};

http://www.other.a.com/b.html中:

document.domain = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘半仙回来了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值