JS8 -- 跨域
1、location.hash + iframe
①.利用 iframe 、 location.hash 传值
②.a访问c,通过b来传播 (a、b同域名,c另外域名)
a.html
a.html 我是a.html页面
b.html
b.html 我是b.html页面
c.html
c.html 我是c.html页面
2、window.name + iframe
window.name 属性的独特之处:name 值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
a页面通过iframe引入c页面,c页面的window.name可以被跨域访问,b页面代理访问window.name,a页面iframe改为b页面间接获取c页面数据
①.利用 iframe 、 window.name 传值
②.a访问c,通过b来传播 (a、b同域名,c另外域名),b是空文件
//a.html DOCTYPE html><html><head><meta charset="utf-8" /><title>a页面title>head><body>a页面<iframe src="http://01.tpqi-e.com/c.html" frameborder="0" onload="load()" id="iframe">iframe><script type="text/javascript">let first = true// onload事件会触发2次,第1次加载跨域页,并留存数据于window.namefunction load() {if(first){// 第1次onload(跨域页)成功后,切换到同域代理页面 let iframe = document.getElementById('iframe');iframe.src = 'http://www.xiaoheikeji.net/index/b.html';first = false;}else{// 第2次onload(同域b.html页)成功后,读取同域window.name中数据 console.log(iframe.contentWindow.name);}}script> body> html>View Code
//c.html DOCTYPE html><html><head><meta charset="utf-8" /><title>c页面title>head><body>c页面<script type="text/javascript">window.name = '我是c页面的数据哟!'script> body> html>View Code
2、document.domain + iframe
主域名相同,二级域名不同
只需要给页面添加 document.domain ='aokete.com' 表示二级域名都相同就可以实现跨域。
实现原理:两个页面都通过 js 强制设置 document.domain 为基础主域,就实现了同域。
//a.html DOCTYPE html><html><head><meta charset="utf-8" /><title>A页面title>head><body>A页面<iframe src="http://www.aokete.com/b.html" frameborder="0" onload="load()" id="frame">iframe><script>document.domain = 'aokete.com'function load() {console.log(frame.contentWindow.b);}script> body> html>View Code
//b.html DOCTYPE html><html><head><meta charset='utf-8' /><title>B页面title>head><body>B页面<script>document.domain = 'aokete.com'var b = '我是B页面数据';script> body> html>View Code
4.jsonp
