The communication method is different depending on whether the src attribute in the iframe is linked to the same domain or cross-domain link.
1. Communication between father and son pages under the same domain
Parent page parent.html
The code copy is as follows:
<html>
<head>
<script type="text/javascript">
function says(){
alert("parent.html");
}
function callChild(){
myFrame.window.say();
myFrame.window.document.getElementById("button").value="Call end";
}
</script>
</head>
<body>
<input id="button" type="button" value="Call the function in child.html says()" onclick="callChild()"/>
<iframe name="myFrame" src="child.html"></iframe>
</body>
</html>
child.html
The code copy is as follows:
<html>
<head>
<script type="text/javascript">
function says(){
alert("child.html");
}
function callParent(){
parent.say();
parent.window.document.getElementById("button").value="Call end";
}
</script>
</head>
<body>
<input id="button" type="button" value="Call the say() function in parent.html" onclick="callParent()"/>
</body>
</html>
Method call
The parent page calls the child page method: FrameName.window.childMethod();
The child page calls the parent page method: parent.window.parentMethod();
DOM element access
After obtaining the window.document object of the page, you can access the DOM element.
Things to note
To ensure that the operation is performed after the iframe is loaded, if the iframe has not yet been loaded, start calling the methods or variables inside, an error will occur. There are two ways to determine whether an iframe is loading:
1. Use onload event on iframe
2. Use document.readyState=="complete" to judge
2. Cross-domain parent-son page communication method
If the iframe links an external page, the communication method under the same domain name cannot be used because the security mechanism is not used.
Parent page passes data to child pages
The implementation technique is to use the hash value of the location object and pass communication data through it. Add an additional data string after the src of the iframe on the parent page, and then in some way you can get the data here instantly, for example:
1. Set the timer in the subpage through the setInterval method, listen to the changes in location.href to obtain the above data information
2. Then the subpage performs corresponding logical processing based on this data information.
The child page passes data to the parent page
The implementation technique is to use a proxy iframe, which is embedded in the child page and must remain in the same domain as the parent page. Then, through it, it fully utilizes the implementation principle of the first communication method above, passes the data of the child page to the proxy iframe. Then, since the proxy iframe and the main page are in the same domain, the main page can obtain this data using the same domain. Use window.top or window.parent.parent to get a reference to the top-level window object of the browser.