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? 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开发者_Python百科 this belief.
What exactly can and can't be done from within an <iframe>
with respect to the containing page?
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...
.
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. However, there is a way to pass messages between the two using the hash portion of the iframe's url. For iframes on the same domain, see oezi's answer.
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. Here is a good example of that process...
http://www.tagneto.org/blogcode/xframe/ui.html
精彩评论