Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

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?

like image 328
akshat Avatar asked Nov 28 '08 15:11

akshat


People also ask

How do I know if a website is loaded in iframe?

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.

Is iframe used to display a webpage inside another webpage?

An HTML iframe is used to display a web page within a web page.


2 Answers

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.

like image 84
Greg Avatar answered Sep 19 '22 18:09

Greg


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.

like image 35
Konstantin Smolyanin Avatar answered Sep 18 '22 18:09

Konstantin Smolyanin