利用domain+iframe跨域

来源:互联网 发布:如何获得淘宝优惠券 编辑:程序博客网 时间:2024/06/08 01:49

此方法行得通的前提是,不同的域有公共域部分。
我在wamp中配置了两个域名

  1. www.newDomain.com;
  2. www.script.newDomain.com;

他们的公共域为newDomain.com;

下面是具体步骤以及代码:
1. 首先我们要在两个不同域的文档里都设置document.domain=’newDomain.com’;
2. 创建iframe,指定载入文档的url,插入父窗口中,并将它隐藏(这样就会看起来好像什么都没有一样);

//www.newDomain.com/newDomain1/test.html<!doctype html><html>    <head>        <title>newDomain1</title>        <style type="text/css">        </style>    </head>    <body>        <div id="mzz">        </div>        <script>        document.domain='newDomain.com';        var ifr=document.createElement('iframe');        ifr.src="http://www.script.newDomain.com/newDomain2/test.html";        ifr.style.display="none";        ifr.setAttribute('name','ifr1');    //为了在父窗口中根据name属性来获取iframe窗口里的文档;        document.body.appendChild(ifr);        var doamin2cookie;        ifr.onload=function(){            var doc=ifr.contentDocument||ifr.contentWindow.document;            //在这里操作doc,你可以console.log(doc),你会发现这是newDomain2下的html            //如果想在这里操作父窗口的html节点,可以通过document或parent.window.document,你通过console.log()可以发现他是newDomain1下的html,也就是父窗口的。            ifr.onload=null;        }        var ifr1document=ifr1.window.document;        //通过console.log()你可以看出这个name为ifr1子窗口的文档信息,通过他可操作子窗口的html        //若前面不把ifr隐藏,通过ifr1document.getElementById('zzq'),会返回你子窗口文档中id为zzq的节点        //这里获取要注意,获取出来的document可能是还没有加载完全的,最好用个延迟,然后再获取,比如        //window.setTimeout(function(){var ifr1document=ifr1.window.document;},1000);        </script>    </body></html>

下面是另一个域的文档

<!doctype html><html>    <head>        <title>newDomain1</title>        <style type="text/css">        </style>    </head>    <body>        <div id="zzq">        </div>        <script>        document.domain='newDomain.com';        </script>    </body></html>

总结:这个例子如果去掉document.domain=’newDomain.com’;则运行到如下两个涉及跨域的地方会报错。若父与子的窗口是同域,则也不会报错。

var doc=ifr.contentDocument||ifr.contentWindow.document;
ifr1document=ifr1.window.document

快捷操作跨域的cookie

上面提到的是跨域获取了整个文档,现在我想说说,由于cookie是document的属性,当我们获取到另一个域中的document时就可以操作另一个域中的cookie,这一点是web Stroage不能完成的。

下面的代码是上面的一个部分:

ifr.onload=function(){    var doc=ifr.contentDocument||ifr.contentWindow.document;    setCookie(doc,"name","mzz")    console.log(getCookie(doc,"name"));     //mzz,你可以才浏览器中看cookie的是否在另一个文档中存在,结果是存在的。    ifr.onload=null;}

下面是cookie的获取和设置的接口:

function getCookie(doc,name){    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");    if(arr=doc.cookie.match(reg))    return unescape(arr[2]);    else    return null;}function setCookie(doc,name,value){    var Days = 30;    var exp = new Date();    exp.setTime(exp.getTime() + Days*24*60*60*1000);    //这里可以不用指定cookie的域    doc.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";}

这是web Storage不能做到的。

0 0
原创粉丝点击