我的HTML页面中有两个级别的父子iframe层次结构。我希望在其子文档中获取父窗口文档的对象以进行一些操作。我主要使用谷歌浏览器。
parent.document在谷歌浏览器中提供“未定义”,而在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',当我点击'Click Me'按钮时,会出现两个连续的警告框,其中包含'undefined'值。当我在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 :(得分:0)
我会从上到下注入而不是自下而上注入。我会在iFrame中设置一个变量,方法是选择它并将其存储到变量中,如下所示:
var frame = document.getElementById('one');
然后为父母注入一个引用:
frame.contentWindow.frame_parent_reference = window;
然后在下一个子iFrame中执行此操作,将“one”替换为“two”。这样,通过third.html,我们不会要求父级或顶级,但可以执行以下操作:
alert(frame_parent_reference.document);
alert(frame_parent_reference.frame_parent_reference.document);
也许不是超级优雅,但它肯定会给你很多控制(你可以检查自定义引用是否存在以确保安全性)。
祝你好运!