简体   繁体   English

iframe如何访问其父DOM?

[英]How is it possible for an iframe to access its parents DOM?

How is it possible for a script within an <iframe> to have any notion of the page containing it? <iframe>的脚本如何能够包含包含它的页面的任何概念? Can a script in the frame access any context outside of it? 框架中的脚本可以访问它之外的任何上下文吗? What about cross-domain? 跨域怎么样?

Up until now I believed an <iframe> is completely agnostic to the containing page, but I have seen an example which contradicts this belief. 到目前为止,我认为<iframe>与包含页面完全无关,但我看到了一个与此信念相矛盾的例子。

What exactly can and can't be done from within an <iframe> with respect to the containing page? 相对于包含页面,在<iframe>究竟能做什么和不能做什么?

If the content of the iframe and its parent have the same domain, you can access the parent pages DOM from the iframe by using parent.document.getElement... . 如果iframe及其父级的内容具有相同的域,则可以使用parent.document.getElement...从iframe访问父页面DOM。

However you can't do this cross-domain (not even across different subdomains) as it will result in: 但是,您不能执行此跨域(甚至不跨越不同的子域),因为它将导致:

Uncaught DOMException: Blocked a frame with origin "https://example.com" from accessing a cross-origin frame.

Generally, you can't communicate between the two DOMs across domains. 通常,您无法跨域中的两个DOM进行通信。 However, there is a way to pass messages between the two using the hash portion of the iframe's url. 但是,有一种方法可以使用iframe的url的哈希部分在两者之间传递消息。 For iframes on the same domain, see oezi's answer . 对于同一域中的iframe,请参阅oezi的回答

This might be of some help , and there's plenty of other questions on the topic around here. 这可能会有所帮助 ,关于这个主题还有很多其他问题。

If they aren't on the same domain, you can communicate some information through the url fragment/hash. 如果它们不在同一个域中,您可以通过url fragment / hash传递一些信息。 Here is a good example of that process... 这是一个很好的例子......

http://www.tagneto.org/blogcode/xframe/ui.html http://www.tagneto.org/blogcode/xframe/ui.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM