JS cross-domain document.domain

When a browser executes Javascript, for security reasons, two or more pages of different domains are prohibited from interoperating.

Pages of the same domain can operate with each other. For example , two files, parent.html and child.html under q515220999.iteye.com/blog/ 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 is the value of the name attribute of the iframe, not id.
            Because the id cannot get the iframe object under FireFox  
          */  
        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>
 
The above sub-pages and parent pages call each other, click the button to see the effect. 

When the child.html page is deployed to the http://q1.iteye.com/blog directory, and the attribute src of the iframe in parent.html is set to http://q1.iteye.com/blog/child.html
At this time, you can access the corresponding page by visiting parent.html in the browser, so that you can simulate the call between two second-level domain name pages.
If you do not uncomment the document.domain line , the browser will report an error. Next

, uncomment the document.domain line of code in the parent and child pages, and find that JS can call each other. Note: This line of code is required for both files. document.domain can be set. However, due to security restrictions, it is not possible to set any value for the domain. For example, q1.iteye.com, then only the domain can be set to "iteye.com"



// Assume the page is from q515220999.iteye.com
document.domain = 'iteye.com'; // success
document.domain = 'q1.iteye.com'; // failed
document.domain = 'baidu.com'; // failed

The above method can realize the cross-domain mutual call of JS between two second-level domain name pages under the same domain name.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326723386&siteId=291194637