Window.name实现跨域

来源:互联网 发布:黑猫seo技术网 编辑:程序博客网 时间:2024/06/05 10:37

前面讲过用domain+frame实现跨域,下面讲另一种跨域的方法。

之所以可以用window.name实现跨域,最重要的一点是在一个frame中重新载入页面时window.name属性值在前后两个页面都是共享的,因此我们可以载入一个新的页面,然后设置这个name,之后在载出,那么我们就可以获取到跨域页面传给name的值啦。当然用完了iframe就把它删啦,因为name属性是不安全的,其他的页面也会修改name属性,反正也没用啦。

可参照这篇文章

//www.newDomain.com/newDomain1/test.html<!doctype html><html>    <head>        <title>newDomain1</title>        <style type="text/css">        </style>    </head>    <body>        <div id="mzz">            <h1>this newDomain1</h1>        </div>        <script>            var ifr=document.createElement('iframe');            //设置跨域的url            ifr.src="http://www.script.newDomain.com/newDomain2/test.html";            ifr.style.display="none";            document.body.appendChild(ifr);            var doamin2cookie;            var isFirst=true;            var xx;            ifr.onload=function(){                if(isFirst){                    //重新加载url,从跨域的状况回到非跨域的情况                    ifr.contentWindow.location = 'http://www.newDomain.com/newDomain1/test.html';                                isFirst = false;                }else{                    console.log(ifr.contentWindow.name);                    //setCookie("name",ifr.contentWindow.name);                                                                                         ifr.contentWindow.document.write('');                    ifr.contentWindow.close();                    document.body.removeChild(ifr);                    ifr.src = '';                    ifr.onload=null;                }            }           </script>       </body></html
<!doctype html><html>    <head>        <title>newDomain1</title>        <style type="text/css">        </style>    </head>    <body>        <div id="zzq">            <h1>this newDomain2</h1>        </div>        <script>            window.name="我是newDomain2";        </script>    </body></html>
0 0
原创粉丝点击