跨域请求方式三:window.name 跨域实现原理

来源:互联网 发布:少年西游记源码 编辑:程序博客网 时间:2024/05/22 14:13

先引用一段话:

window.name 传输技术,原本是 Thomas Frank 用于解决 cookie 的一些劣势(每个域名 4 x 20 Kb的限制、数据只能是字符串、设置和获取 cookie 语法的复杂等等)而发明的。后来 Kris Zyp 在此方法的基础上强化了 window.name 传输 ,用来解决跨域数据传输问题。

window.name 的美妙之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。

window.name 传输技术的基本原理:
当在浏览器中打开一个页面,或者在页面中添加一个iframe时即会创建一个对应的window对象,当页面加载另一个新的页面时,window的name属性是不会变的。这样就可以利用在页面动态添加一个iframe然后src加载数据页面,在数据页面将需要的数据赋值给window.name。然而此时承载iframe的parent页面还是不能直接访问,不在同一域下iframe的name属性,这时只需要将iframe再加载一个与承载页面同域的空白页面,即可对window.name进行数据读取

示例:

www.test.com下a.html页:

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <button>click!</button>        <script type="text/javascript">            var a=document.getElementsByTagName("button")[0];            a.onclick=function(){                               //button添加click事件                var inf=document.createElement("iframe");       //创建iframe                inf.src="http://www.domain.com/window.name/b.html"+"?h=5"  //加载数据页www.domain.com/window.name/b.html同事携带参数h=5                var body=document.getElementsByTagName("body")[0];                body.appendChild(inf);                          //引入a页面                inf.onload=function(){                    inf.src='http://www.test.com/b.html'       //iframe加载完成,加载www.test.com域下边的空白页b.html                    console.log(inf.contentWindow.name)        //输出window.name中的数据                    body.removeChild(inf)                      //清除iframe                }            }        </script>    </body></html>

www.domain.com下b.html页:

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <a href="" target="" title="">2</a>        <script type="text/javascript" src="../cross/jquery-2.2.3.js">        </script>        <script>            var str=window.location.href.substr(-1,1);      //获取url中携带的参数值            $.ajax({                type:"get",                url:"http://www.domain.com/a.php"+"?m="+str, //通过ajax将查询参数传给php页面                async:true,                success:function(res){                    window.name=res                         //将接收到的查询数据赋值给window.name                },                error:function(){                    window.name='error'                      //..                }            });        </script>    </body></html>

在www.test.com下a页面点击button,完美跨域获取到了www.domain.com下b页面通过ajax请求从a.PHP得来的数据。

0 0
原创粉丝点击