iframe与主框架跨域如何相互访问2015-06-191.同域相互访问假设A.html 与 b.html domain都是localhost (同域)A.html中iframe 嵌入 B.html,name=myframeA.html有js function fMain()B.html有js function fIframe()需要实现 A.html 调用 B.html 的 fIframe(),B.html 调用 A.html 的 fMain()A.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head><meta http-equiv="content-type" content="text/html; charset=utf-8"><title> main window </title><script type="text/javascript">// main js functionfunction fMain(){alert("main function execute success");}// exec iframe functionfunction exec_iframe(){window.myframe.fIframe();}</script> </head> <body><p>A.html main</p><p><input type="button" value="exec iframe function" onclick="exec_iframe()"></p><iframe src="B.html" name="myframe" width="500" height="100"></iframe> </body></html>B.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head><meta http-equiv="content-type" content="text/html; charset=utf-8"><title> iframe window </title><script type="text/javascript">// iframe js function function fIframe(){alert("iframe function execute success");}// exec main functionfunction exec_main(){parent.fMain();}</script> </head> <body><p>B.html iframe</p><p><input type="button" value="exec main function" onclick="exec_main()"></p> </body></html>点击A.html 的 exec iframe function button,执行成功,弹出iframe function execute success。如下图