iframe和父页,window.open打开页面之间的引用

【转】iframe和父页,window.open打开页面之间的引用

iframe和父页,window.open打开页面和被打开页面之间的关系可以通过下面的对象获取到

  1)通过iframe加载的,在iframe中用parent对象得到父页window作用域,如果iframe中又加载了iframe,在最里层的iframe中需要重复调用parent.parent得到其上一级iframe的引用。如果是直接引用最顶级的父页作用域,可以使用top对象。

  2)父页使用document.getElementById(“iframe的id”).contentWindow得到iframe的window作用域,如果iframe还继续嵌套了iframe,则还需要继续执行.getElementById(“iframe的id”).contentWindow操作才能得到内层iframe的作用域。如:

1 var ifrWin=document.getElementById("iframe的id").contentWindow.getElementById("再次被嵌套的iframe的id").contentWindow;

  

  3)aaa.html中使用 var win=window.open(“xxx.html”),win就是xxx.html的window作用域,xxx.html中使用opener对象得到打开这个页面的window作用域。如果xxx.html又打开了bbb.html,那么bbb.html中使用opener.opener得到aaa.html作用域,aaa.html要想得到bbb.html作用域,那么xxx.html需要保存打开bbb.html的作用域如var win=window.open(“bbb.html”),那么aaa.html通过win.win就得到bbb.html的作用域了.


  通过上面的介绍知道了关系之后,就很容易从一个页面更新到其他通过window.open或者iframe嵌套的子页面或者父页面了。

  备注:chrome浏览器下本地测试iframe不能互访,chrome浏览器iframe parent.document为undefined.

  测试脚本的时候发现,在谷歌chrome浏览器下面,iframe中获取父页的document时竟然为undefined,google chrome神奇了,其他浏览器如ie,firefox没出现这种问题。

  iframe要获取到父页的document对象,需要通过服务器,就是http协议访问时才能获取到,要不直接双击运行【chrome为默认浏览器】或者直接拖进chrome浏览器查看时,iframe使用parent.document得到的是undefined。

测试代码:

test.html

复制代码
1 <html>
2    <head></head>
3    <body><input type="text" id="txt" />
4    <br />
5    <iframe src="ifr.html"></iframe></body>
6 </html>
复制代码

ifr.html

复制代码
1 <input type="button" onclick="setValue()" value="设置父页输入框内容" />
2 <script>
3     function setValue() {
4         alert(parent.document)  //非http协议访问输出undefined,http协议访问时输出[object HTMLDocument]
5         var ipt = parent.document.getElementById('txt');  //本地浏览由于parent.document为undefined,所以当然无法使用getElementById方法了
6         ipt.value = new Date().toLocaleString();
7     }
8 </script>
复制代码

EOM

原文转自编程设计网,文章所有权,解释权归原作者。

Lionden 2015年8月9日

E-mail:[email protected] 

转载请注明原文地址和博客园Liondenhttp://www.cnblogs.com/lionden/ 

猜你喜欢

转载自blog.csdn.net/qq_38643434/article/details/81430521