15

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?)?

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?

Community
  • 1
  • 1
stiank81
  • 25,418
  • 43
  • 131
  • 202

1 Answers1

26

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:

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thx! The domains doesn't match, so that's obviously a problem. Now that you say it I know that I've read about this a while back. When the domains don't match you can't access the parents document. So my problem can't be solved when the framed content is on different domains. Right? – stiank81 Nov 10 '11 at 07:56
  • There are some tricks to still communicate across different domains. Have a look at [this lengthy article](http://softwareas.com/cross-domain-communication-with-iframes). If both pages are served at the same domain, but with a different subdomain, setting the [`document.domain`](https://developer.mozilla.org/en/DOM/document.domain) will help. Otherwise, if you are the owner of both websites, you can implement [`window.postMessage`](https://developer.mozilla.org/en/DOM/window.postMessage). – Rob W Nov 10 '11 at 08:56