I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?
Browsers can block access to window.top
due to same origin policy. IE bugs also take place. Here's the working code:
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
top
and self
are both window
objects (along with parent
), so you're seeing if your window is the top window.
This seems to work fine in Firefox. Does it work in other browsers too?
Having a page with an iframe within an iframe, to test from my child iframe if my parent iframe was embeded in the page, I used if (parent === top)
@sglessard If the child page and parent are from different domains then Firefox will complain for Same Origin Policy (www.w3.org/Security/wiki/Same_Origin_Policy) and code won't work
This works in IE 11, 10, and 9 for me. Also it works in FF and Opera as well as, of course, Chrome. I haven't run into any issues with it.
For those still rocking the latest in 1995 tech,
window.self !== window.top
returnstrue
when run from within contents offrame
, oriframe
.