views:

91

answers:

3

I need the script to dynamically change how it functions if the page is embedded via an iFrame.

The script will be called in the iFrame source from a <script.. tag and wont be inline javascript.

Thank You in Advance!

Update: David provided this answer which works in Firefox and Chrome but doesn't work in IE8, any help with this is appreciated : )

if (window !== top) {
  alert('im in an frame');
}

Update2: Apparently this is a duplicate question, the right answer is:

if (top === self) { alert('parent'); } else { alert('iframe'); }

Credit goes to Greg

+3  A: 
if (window != top) {
  // In a frame of some kind
}
David Dorward
I think StackOverflow implements this method. `<iframe src="http://stackoverflow.com"/>`
Andy E
hmm, works great in chrome and firefox, doesn't seem to work in IE8, thanks though!
Mohammad
`if (window !== top) {alert(window);}` returns `[object]` from the page and `[object Window]` from the iFrame in IE (not working correctly), in firefox only the second is returned (working correctly) and in chrome `[object DOMWindow]` is returned (also working correctly). I hope this helps. (btw the window.parent suggestion fails to work in both firefox and chrome)
Mohammad
Actually there is a super easy answer to this.. you could always test `window.location.hostname` against the expected address of your domain to see if the page is being embedded. This seems a bit fragile though. And could introduce unwanted behavior in the future with domain name change.
Mohammad
David please read the updated question.
Mohammad
A: 

IE does not return true for the equivalence operator (===) for two references to the same window object- even in a top level window, if(window===top) returns false.

But the simpler equality operator if(window==top) returns true in all the browsers if the object is the top window, and false if it is an iframe contained in a window.

kennebec
Actually it seems to return true in both cases, I just tested it. Thanks tho!
Mohammad
A: 
if (top === self) { alert('parent'); } else { alert('iframe'); }  

Works fine! Credit goes to Greg

Mohammad