JS跨域之document.domain

浏览器在执行Javascript时,出于对安全性的考虑,禁止两个或者多个不同域的页面进行互相操作。

相同域的页面可以相互操作。 如在 q515220999.iteye.com/blog/下的parent.html和child.html两个文件

1. parent.html
<!DOCTYPE html>  
<html>  
<head>  
<meta charset=utf-8/>  
<title>parent</title>  
<script>  
    // document.domain = "iteye.com";  
    function parentFunction() {  
        alert('function in parent');  
    }  
  
    function callChild() {  
         /*  
            child 为iframe的name属性值,不能为id.
            因为在FireFox下id不能获取iframe对象  
          */  
        child.window.childFunction();  
    }  
</script>  
</head>  
<body>  
<input type="button" name="call child"  value="call child" onclick="callChild()"/>    
<iframe name="child" src="child.html" >  
</iframe>  
</body>  
</html>  


2.child.html
<!DOCTYPE html>  
<html>  
<head>  
<meta charset=utf-8/>  
<title>child</title>  
<script>  
    // document.domain = "iteye.com";  
    function childFunction() {  
        alert('function in child');  
    }  

    function callParent() {  
        parent.parentFunction();  
    }  
</script>  
</head>  
<body>  
<input type="button" name="call parent" value="call parent" onclick="callParent()"/>  
</body>  
</html>
 
以上的子页面和父页面之间相互调用,点击按钮即可看到效果。 

当将child.html页面部署到http://q1.iteye.com/blog目录下,且将parent.html中的iframe的属性src设置为http://q1.iteye.com/blog/child.html
此时在浏览器中访问parent.html即可访问到对应页面,这样就可以模拟两个二级域名页面之间的调用了。
如果 没有去掉document.domain 这行的注释,浏览器会报错。

接下来 取消注释parent与child页面中的 document.domain 这行代码,发现JS可以相互调用了。
注:两个文件都需要这行代码。

document.domain是可以设置的。但由于安全方面的限制,也也并非可以给domain设置任何值。例如q1.iteye.com,那么只能将domain设置为“iteye.com”
 // 假设页面来自q515220999.iteye.com
document.domain = 'iteye.com';    // 成功
document.domain = 'q1.iteye.com';    // 失败
document.domain = 'baidu.com';    // 失败

以上方法可以实现同一个域名下两个二级域名页面之间JS的跨域相互调用。

猜你喜欢

转载自q515220999.iteye.com/blog/2369096