首先我们设置三个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>
<!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