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

执行如下图:

源码下载地址:

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...