Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 this belief.

What exactly can and can't be done from within an <iframe> with respect to the containing page?

like image 711
Yuval Adam Avatar asked Apr 12 '10 08:04

Yuval Adam


People also ask

Can iframe access parent variables?

So, for instance, if you define a var myvar = 2 in the parent scope, you can access that in the iframe as window. parent. myvar.

How can an iframe communicate with its parent?

All you have to do is first dispatch an event from the iframe to the parent that notifies the parent that the iframe is loaded (essentially a "ready message"). The parent will be listening for messages and if it receives the "ready message" event, it can then reply to the iframe with whatever message you want to send.

Can iframe access the cookies of parent?

You can only read the cookie of the iframe within the same iframe only and after reading you can pass the cookie value to the parent window using the postMessage.

How do I stop iframe from accessing my parents?

The spec says that if the "allow-same-origin" attribute is not set, "the content is treated as being from a unique origin." This should prevent your child iframe from accessing any part of the parent's DOM, no matter what the browser thinks the URL is.


2 Answers

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.
like image 112
oezi Avatar answered Sep 20 '22 17:09

oezi


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.

like image 29
Olly Hodgson Avatar answered Sep 21 '22 17:09

Olly Hodgson