window.name跨域
首先,当我们尝试去查看一个普通页面下,window的属性时候,确实存在name属性,并且值为空。那么,这个window.name存在的意义是什么呢?就如同标题所讲,可以解决跨域问题。那么,我们下面详细讲解下如何利用window.name跨域。
引例
- 前提准备:
- a.html,起在localhost:3000上
- b.html,起在localhost:3000上
- c.html,起在localhost:4000上
可见a和b是同域的,c是独立的
- 需求:在a页面获取c页面发送的数据。
- 思路:a先引用c,c把值放到window.name中,然后把a引用的地址改到b
- 代码:
//a.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>a.html</title> </head> <body> <iframe id="iframe" src="http://localhost:4000/c.html" frameborder="0" "load()"></iframe> <script type="text/javascript"> let first = true;//第一次加载 function load(){ if(first){ let iframe = document.querySelector("#iframe"); iframe.src = 'http://localhost:3000/b.html'; first = false; }else{ console.log(iframe.contentWindow.name);//yuhua } } </script> </body> </html> //b.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html> //c.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> c页面 <script type="text/javascript"> window.name = 'yuhua'; </script> </body> </html>
- 现象:通过c.html设置window.name=‘yuhua’,然后a.html会打印’yuhua’
- 原因分析:
window.name有如下特征:
1. 每个窗口都有自己独立的window.name
2. 当一个页面载入多个页面的时候,共享同一个window.name,该页面以及所有载入的页面都可以对共享的window.name进行读写。
3. window.name一直会存在当前窗口中,即时有新页面载入,window.name也不会变化(所以本例中,c页面给window.name一个值,即便c页面销毁,a页面依旧能够得到window.name,且该值就是c页面给的这个值)
4. window.name可以存储不超过2M的数据,传递的数据都会变成string类型。
以上原因分析4点均为重点
实现跨域的9种方法(点击可跳转详情页面)
- jsonp
- cors
- postMessage
- document.domain
- window.name
- location.hash
- http-proxy 后续会有详细文章阐述
- nginx 后续会有详细版块阐述
- websocket