微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

iframe与主框架跨域相互访问实现方法

1.同域相互访问

假设A.html 与 b.html domain都是localhost (同域) A.html中iframe 嵌入 B.html,name=myframe A.html有js function fMain() B.html有js function fIframe() 需要实现 A.html 调用 B.html 的 fIframe(),B.html 调用 A.html 的 fMain()

A.html

rush:xhtml;"> <Meta http-equiv="content-type" content="text/html; charset=utf-8"> main window

<script type="text/javascript">
// main js function
function fMain(){
alert('main function execute success');
}

// exec iframe function
function exec_iframe(){
window.myframe.fIframe();
}

A.html main

B.html

rush:xhtml;"> <Meta http-equiv="content-type" content="text/html; charset=utf-8"> iframe window

<script type="text/javascript">
// iframe js function
function fIframe(){
alert('iframe function execute success');
}

// exec main function
function exec_main(){
if(typeof(exec_obj)=='undefined'){
exec_obj = document.createElement('iframe');
exec_obj.name = 'tmp_frame';
exec_obj.src = 'http://localhost/execA.html';
exec_obj.style.display = 'none';
document.body.appendChild(exec_obj);
}else{
exec_obj.src = 'http://localhost/execA.html?' + Math.random();
}
}

B.html iframe

execA.html

rush:js;"> <Meta http-equiv="content-type" content="text/html; charset=utf-8"> exec main function

执行如下图:

源码下载地址:

原文地址:https://www.jb51.cc/js/36399.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐