iframe子页面与父页面通讯根据iframe中src属性是同域连接仍是跨域连接,通讯方式也不一样。javascript
<html> <head> <script type="text/javascript"> function say(){ alert("parent.html"); } function callChild(){ myFrame.window.say(); myFrame.window.document.getElementById("button").value="调用结束"; } </script> </head> <body> <input id="button" type="button" value="调用child.html中的函数say()" onclick="callChild()"/> <iframe name="myFrame" src="child.html"></iframe> </body> </html>
<html> <head> <script type="text/javascript"> function say(){ alert("child.html"); } function callParent(){ parent.say(); parent.window.document.getElementById("button").value="调用结束"; } </script> </head> <body> <input id="button" type="button" value="调用parent.html中的say()函数" onclick="callParent()"/> </body> </html>
父页面调用子页面方法:FrameName.window.childMethod();html
子页面调用父页面方法:parent.window.parentMethod();java
获取到页面的window.document对象后,便可访问DOM元素跨域
要确保在iframe加载完成后再进行操做,若是iframe还未加载完成就开始调用里面的方法或变量,会产生错误。判断iframe是否加载完成有两种方法:浏览器
1. iframe上用onload事件安全
2. 用document.readyState=="complete"来判断函数
若是iframe所连接的是外部页面,由于安全机制就不能使用同域名下的通讯方式了。spa
实现的技巧是利用location对象的hash值,经过它传递通讯数据。在父页面设置iframe的src后面多加个data字符串,而后在子页面中经过某种方式能即时的获取到这儿的data就能够了,例如:代理
1. 在子页面中经过setInterval方法设置定时器,监听location.href的变化便可得到上面的data信息htm
2. 而后子页面根据这个data信息进行相应的逻辑处理
实现技巧就是利用一个代理iframe,它嵌入到子页面中,而且和父页面必须保持是同域,而后经过它充分利用上面第一种通讯方式的实现原理就把子页面的数据传递给代理iframe,而后因为代理的iframe和主页面是同域的,因此主页面就能够利用同域的方式获取到这些数据。使用 window.top或者window.parent.parent获取浏览器最顶层window对象的引用。