iframe子页面与父页面的通信早就被研究透彻了,之前一直没有用到这个内容所以也没有去研究,今天突然遇到一道题目,所以稍微试了一下,跨域通信使用了来自腾讯团队给出的messenger.js,源码也很简单值的一看,官方给出的demo很全面,此处我只是给出了一个简单的例子。
<!DOCTYPE html><html><head><title>iframe子页面与父页面通信(同域)</title><meta charset="utf-8"><script type="text/javascript">
function sayHello(){
alert("iframeCommunication1.html");
} function say(){
child1.window.sayHello();
child1.window.document.getElementById("button_c").value = "the call is complete";
}</script></head><body><h1>iframe子页面与父页面同域通信</h1>调用子页面child1.html中的sayHello()函数:<input type="button" id="button_p" name="hello" value="call" onclick="say()"><br><br><iframe src="child1.html" id="child1"></iframe></body></html><!DOCTYPE html><html><head><title>iframe子页面与父页面通信(同域)</title><meta charset="utf-8"><script type="text/javascript">
function sayHello(){
alert("child.html");
} function say(){
parent.sayHello();
parent.window.document.getElementById("button_p").value = "the call is complete";
}</script></head><body><p>调用父页面iframeCommunication1.html中的sayHello()函数:</p><input type="button" id="button_c" name="hello" value="call" onclick="say()"></body></html>对于IE8+及现代浏览器,跨域通信主要使用了html5给出的postMessage API来实现域间通信。postMessage的功能是允许程序员跨域在两个窗口/frames间发送数据信息。基本上,它就像是跨域的AJAX,但不是浏览器跟服务器之间交互,而是在两个客户端之间通信。
对于旧版浏览器,messenger.js使用了navigator对象在父窗口和iframe之间是共享的特性,在navigator对象上注册消息回调函数实现信息传递及共享。
下面给出一个很简单的例子:
<!DOCTYPE html><html><head><title>iframe子页面与父页面通信(跨域)</title><meta charset="utf-8"><script src="js/messenger.js"></script></head><body><h1>iframe子页面与父页面跨域通信</h1>向子页面child2.html发送信息:<input type="button" id="button_p" value="call" onclick="sendMessage('child2')"><br><br>获取信息:<pre class="brush:php;toolbar:false;" id="output">以上就是iframe子、父页面域内及跨域通信实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号