2013-03-26 102 views
0

我的HTML頁面中有兩級父 - 子iframe層次結構。我想在其子文檔中獲取父窗口文檔的對象以進行一些操作。我主要與Google Chrome合作。parent.document在Chrome中未定義

parent.document在Google Chrome中給出'undefined',而在Mozilla中它可以正常工作。有什麼收穫?

僅供參考,請找三個文件證明問題的內容下方,

第一個文件: 'one.html'

<html> 
<head> 
</head> 
<body> 
    <input type="hidden" id="one_1" name="one_1" /> 
    <iframe id="one" name="one" src="two.html"> 
</body> 
</html> 

第二個文件: 'two.html'

<html> 
<head> 
</head> 
<body> 
    <input type="hidden" id="two_1" name="two_1" /> 
    <iframe id="two" name="two" src="three.html"> 
</body> 
</html> 

第三個文件: 'three.html'

<html> 
<head> 
<script type="text/javascript"> 

    function callme() { 
     alert(parent.document) 
     alert(top.document) 
    } 
</script> 
</head> 
<body> 
    <input type="hidden" id="three_1" name="three_1" /> 
    <button id="click" name="click" onclick="return callme()">Click Me</button> 
</body> 
</html> 

假設「one.html」打開谷歌瀏覽器,當我點擊「點擊我」按鈕,兩個連續的警報框將出現與「未定義」值。當我在Mozilla中打開'one.html'時,會出現兩個'objectHTMLDocument'值的警告框。

請找到控制檯消息之下,而點擊「點擊我」按鈕,提前

Unsafe JavaScript attempt to access frame with URL file:///C:/Users/user/Desktop/two.html from frame with URL file:///C:/Users/user/Desktop/three.html. Domains, protocols and ports must match. 
                   three.html:6 
callme               three.html:6 
onclick               three.html:13 

Unsafe JavaScript attempt to access frame with URL file:///C:/Users/user/Desktop/one.html from frame with URL file:///C:/Users/user/Desktop/three.html. Domains, protocols and ports must match. 
                   three.html:7 
callme               three.html:7 
onclick               three.html:13 

感謝。

+0

這個問題是['contentDocument'](https://developer.mozilla.org/en-US/docs/HTML/Element/iframe#Scripting)。 – bfavaretto 2013-03-26 20:08:01

+0

@bfavaretto剛剛檢查過contentDocument,仍然沒有收穫:( – dsharma4u29 2013-03-26 20:09:39

+0

您能否顯示您的代碼? – bfavaretto 2013-03-26 20:10:45

回答

0

我會從上而下注入,而不是自下而上。我將設置在一個iFrame的變量通過選擇它,並將其存儲到一個變量,像這樣:

var frame = document.getElementById('one'); 

然後注入到父的引用:

frame.contentWindow.frame_parent_reference = window; 

然後在下一執行此兒童iFrame用「two」代替「one」。這樣一來,通過third.html,我們不要求父母或頂部,但能做到以下幾點:

alert(frame_parent_reference.document); 
alert(frame_parent_reference.frame_parent_reference.document); 

也許不是超級優雅,但它肯定給你很多控制的(你可以檢查自定義引用存在安全性)。

祝你好運!

相關問題