关于跨域中document.domain的设置问题

首先我们设置三个host

127.0.0.1 a.domain.com
127.0.0.1 b.domain.com
127.0.0.1 c.domain.com

然后写如下测试页面http://a.domain.com/test.html

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
    html,body{
        height: 100%
    }
</style>    
</head>
<body>
<script type="text/javascript" src="jquery-2.2.3-unzip.js"></script>
<div style="width: 100px;">click</div>
<script type="text/javascript">
    document.domain = 'domain.com';
    $('div').on('click', function() {
        console.log($('#domainb')[0].contentWindow.name)
    })
</script>
<iframe id = "domainb" src="http://b.domain.com/test.html" style="height: 100%;width: 100%"></iframe>
</body>
</html>

http://b.domain.com/test.html

<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
document.domain = 'domain.com';
var name = 'b.domain.com'
</script>
</body>
</html>

通过设置document.domain,我们完成了跨域通信,但是因为我们的页面设置了document.domain为domain.com,如果此时有个域名c.domain.com,也能完成和b.domain.com下页面的通信,所以任何以domain.com结尾的站点,都可以这样。这时候如果c.domain.com下有一个页面是index.html,然后在利用iframe嵌入a.domain.com的页面,那就可以完成对a.domain.com站点数据的窃取,比如用户的登录数据。所以设置document.domain = x的时候,要不然我们把以x为后缀的域名都买下来,要不然我们就要设置禁止我们站点的页面内嵌在其他域名的页面里。
c.domai.com/test.html

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
    html,body{
        height: 100%
    }
</style>
<script type="text/javascript" src="jquery-2.2.3-unzip.js"></script>
    <title></title>
</head>
<body>
<div style="width: 100px;">click</div>
<script type="text/javascript">
    document.domain = 'domain.com';
    $('div').on('click', function() {
        console.log($('#domainb')[0].contentWindow.document.cookie)
    })
</script>
<iframe id = "domainb" src="http://b.domain.com/test.html" style="height: 100%;width: 100%"></iframe>
</body>
</html>

另外设置document.domain的另一个问题是一旦设置了,就无法恢复到原来的值。
http://a.domain.com/test.html

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
    html,body{
        height: 100%
    }
</style>
<script type="text/javascript" src="jquery-2.2.3-unzip.js"></script>

</head>
<body>
<div style="width: 100px;">click</div>
<script type="text/javascript">
    document.domain = 'domain.com';
    $('div').on('click', function() {
        console.log($('#domainb')[0].contentWindow.name)
    })
</script>
<iframe id = "domainb" src="http://b.domain.com/test.html" style="height: 100%;width: 100%"></iframe>
<iframe id = "domainb" src="http://a.domain.com/test2.html" style="height: 100%;width: 100%"></iframe>
</body>
</html>

该页面设置了document.domain,完成了和b.domain.com的通信,但是因为他的修改导致原来的同源策略的主机匹配规则被覆盖,所以和a.domain.com下的页面被认为是非同源,导致无法访问同域下的页面,除非每个页面都设置document.domain

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值