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?
In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.
An HTML iframe is used to display a web page within a web page.
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.
When in an iframe on the same origin as the parent, the window.frameElement
method returns the element (e.g. iframe
or object
) in which the window is embedded. Otherwise, if browsing in a top-level context, or if the parent and the child frame have different origins, it will evaluate to null
.
window.frameElement ? 'embedded in iframe or object' : 'not embedded or cross-origin'
This is an HTML Standard with basic support in all modern browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With