您的位置:首页 > 其它

Window.name实现跨域

2016-04-14 23:08 387 查看
前面讲过用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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  跨域