如何通过链接在两个iframe间传递数据?示例实现
如何在两个iframe间通过链接传递数据并调用目标函数
前提说明
仅当两个iframe与主页面处于同一域名时,才能直接通过window对象互相访问(浏览器同源策略限制)。如果是跨域场景,建议用postMessage方案。
方案一:直接调用目标iframe的函数(同域)
修改top.php中的文本为可点击的链接,通过主页面的window对象直接调用底部iframe的playSong函数:
修改后的top.php代码:
<html> <head> </head> <body> <a href="javascript:void(0);" onclick="parent.frames['BottomFrame'].playSong('歌曲1');">点击播放歌曲1</a><br> <a href="javascript:void(0);" onclick="parent.frames['BottomFrame'].playSong('歌曲2');">点击播放歌曲2</a><br> <a href="javascript:void(0);" onclick="parent.frames['BottomFrame'].playSong('歌曲3');">点击播放歌曲3</a><br> </body> </html>
代码说明
javascript:void(0);:阻止链接默认的跳转行为,避免页面刷新parent:当前iframe(top.php所在的MainFrame)的父窗口,也就是主页面的window实例frames['BottomFrame']:通过iframe的name属性,获取底部iframe的window对象- 直接调用该window上的
playSong函数,传入歌曲名称作为参数
方案二:使用postMessage传递数据(支持跨域)
如果需要支持跨域场景,或者希望更规范地传递数据,推荐使用postMessage API:
步骤1:修改top.php的链接
<html> <head> </head> <body> <a href="javascript:void(0);" onclick="parent.postMessage({action: 'playSong', song: '歌曲1'}, '*');">点击播放歌曲1</a><br> <a href="javascript:void(0);" onclick="parent.postMessage({action: 'playSong', song: '歌曲2'}, '*');">点击播放歌曲2</a><br> <a href="javascript:void(0);" onclick="parent.postMessage({action: 'playSong', song: '歌曲3'}, '*');">点击播放歌曲3</a><br> </body> </html>
步骤2:在主页面index.html中添加消息监听
给底部iframe添加id属性,方便获取实例,同时添加消息监听转发数据:
<html> <head> <style> html,body {height:100%;} .h_iframe1 iframe {position:absolute;top:0;left:0;width:100%; height:calc(100% - 60px);} .h_iframe2 iframe {position:absolute;bottom:0;right:0;width:100%; height:60px;} </style> <script> window.addEventListener('message', function(event) { // 生产环境建议验证event.origin,只允许指定域名的消息,避免安全风险 // if (event.origin !== 'https://your-domain.com') return; if (event.data.action === 'playSong') { document.getElementById('BottomFrame').contentWindow.playSong(event.data.song); } }); </script> </head> <body> <div class="wrapper"> <div class="h_iframe1"> <iframe name="MainFrame" src="top.php" frameborder="0" allowfullscreen></iframe> </div> </div> <div class="wrapper"> <div class="h_iframe2"> <iframe id="BottomFrame" name="BottomFrame" src="bottom.php" frameborder="0" allowfullscreen></iframe> </div> </div> </body> </html>
代码说明
postMessage:第一个参数是要传递的数据对象,第二个参数是目标域名,*表示允许所有域名(生产环境务必替换为具体域名,提升安全性)- 主页面监听
message事件,接收顶部iframe发来的消息,判断消息类型后,调用底部iframe的playSong函数
内容的提问来源于stack exchange,提问作者GETaPED
相关产品推荐
相关产品推荐

