Javascript 从 iFrame 获取父文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8066547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting parents document from iFrame
提问by stiank81
I have seen some elegant solutions on fetching the parents document from iframe - like e.g. this one. However, I can't make it work - and I didn't think this was possible due to securities issues (cross domain scripting?)?
我已经看到了一些从 iframe 获取父文档的优雅解决方案 - 例如这个。但是,我无法让它工作 - 我认为这是不可能的,因为证券问题(跨域脚本?)?
My question is; can I still access the parents document from inside an iframe - or has this changed the recent years? If I should be able to access this; any thoughts on why I get undefined when printing parent.document
or window.parent.document
from the content of the iframe?
我的问题是;我是否仍然可以从 iframe 内部访问父文档 - 或者近年来这是否发生了变化?如果我应该能够访问它;关于为什么我在打印时parent.document
或window.parent.document
从 iframe 的内容中未定义的任何想法?
回答by Rob W
It's still possible to access the parent from within a frame provided that the domains match.
如果域匹配 ,仍然可以从框架内访问父级。
For example, have a look at these fiddles:
例如,看看这些小提琴:
- Frame host:
fiddle.jshell.net
, parent host:fiddle.net
Does not match = failure
Test #1: http://jsfiddle.net/nrRQg/1/ - Frame host:
jsfiddle.net
, parent host:jsfiddle.net
**Matches = success*
Test #2: http://jsfiddle.net/nrRQg/1/show/
- 帧主机:
fiddle.jshell.net
,父主机:fiddle.net
不匹配 = 失败
测试 #1:http: //jsfiddle.net/nrRQg/1/ - 框架主机:
jsfiddle.net
,父主机:jsfiddle.net
**匹配 = 成功*
测试 #2:http: //jsfiddle.net/nrRQg/1/show/
You can access the parent through:
您可以通过以下方式访问父级:
window.parent
parent
top //If the parent is the top-level document
window.top
The variables parent
and top
can be overwritten (usually not intended). It's safer to use window.parent
to be more safe. Alternatively, you can replace window
by document.defaultView
.
变量parent
和top
可以被覆盖(通常不是故意的)。使用window.parent
更安全更安全。或者,您可以替换window
为document.defaultView
。