21

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?

leonheess
  • 16,068
  • 14
  • 77
  • 112
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395

3 Answers3

43

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.
leonheess
  • 16,068
  • 14
  • 77
  • 112
oezi
  • 51,017
  • 10
  • 98
  • 115
  • 18
    just for reference, `top` is the top document, `self` is the current document and `parent` is the document above the current one. – cryo Apr 12 '10 at 09:08
  • Learn something new every day :) – Olly Hodgson Apr 12 '10 at 09:46
  • @oezi, I have a document that loads iframe from a different domain. I was able to manipulate the iframe attributes from within the document loaded in that iframe. I used parent.document.getElementById() to get the element and then add an attribute using $(ele).attr('width','100%'); I have no clue why it worked for me. Let me know if you want to know any specifics of my environment to have better idea of this problem. Thanks – Rishabh Jun 30 '14 at 20:47
  • @Rishabh which browser did you use? – lulalala Aug 20 '15 at 03:23
5

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.

Community
  • 1
  • 1
Olly Hodgson
  • 15,076
  • 3
  • 40
  • 60
  • interesting article, strange that it dismisses html5's postmessage as having not enough support yet as safari, chrome, firefox, opera and even MSIE8 support it. with the jquery postmessage plugin (which uses some of the techniques used in the article you link) it becomes entirely cross-browser. – futtta Apr 12 '10 at 09:27
  • I think that's understandable - it was written in March 2008 :) That jQuery plugin sounds very interesting though. – Olly Hodgson Apr 12 '10 at 09:45
2

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

John Himmelman
  • 21,504
  • 22
  • 65
  • 80