【轉】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:hsdlionden@hotmail.com
轉載請注明原文地址和博客園Lionden:http://www.cnblogs.com/lionden/