769

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?

akshat
  • 15,472
  • 8
  • 30
  • 29
  • 3
    A few nice ways (including comments): https://tommcfarlin.com/check-if-a-page-is-in-an-iframe/ – simhumileco Jan 20 '19 at 08:03
  • 2
    External links aren't a very good way of answering questions. Especially if the content of those external links can be reduced to `return window.location !== window.parent.location`. – Dan Atkinson Sep 17 '21 at 09:05

18 Answers18

1390

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.

James Gentes
  • 7,528
  • 7
  • 44
  • 64
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 5
    This seems to work fine in Firefox. Does it work in other browsers too? – akshat Nov 28 '08 at 15:51
  • 8
    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 Mar 27 '12 at 14:31
  • 8
    @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 – Gaurang Jadia Jul 31 '12 at 22:10
  • 28
    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. – jeremysawesome Aug 22 '13 at 16:40
  • 1
    @MNVOH, tripple check this in IE8 – Dan Jan 13 '14 at 09:57
  • 1
    @MNVOH Updated the solution, please check it out. – Dan Jan 13 '14 at 10:35
  • 1
    The last update is causing an error for me. Doesn't catch require a parameter? – Mike Jan 16 '14 at 18:44
  • Yeah, I'm pretty sure catch requires a parameter... Not working as-is for me, either. – rinogo Jan 20 '14 at 21:04
  • 1
    This will fail if origins match. Window.top will be available to the iframe. – Jabran Saeed Mar 04 '14 at 03:50
  • I thought this wasn't working on IE11 (Windows 7), _unless_ I enabled the dev console; then it did work. Turns out my code had a "console.log" to show me what was happening in the logic, and it looks like IE11 throws if you call console.log and there is no console attached. Without logging, this works for me in Chrome, Firefox, IE11 and Safari (Windows 7 and OSX where appropriate). – Andrew Richard Miller Feb 08 '16 at 10:09
  • 14
    For those still rocking the latest in 1995 tech, `window.self !== window.top` returns `true` when run from within contents of `frame`, *or* `iframe`. – Jeromy French Mar 23 '17 at 20:13
  • 1
    "Browsers can block access to window.top due to same origin policy." Are you sure? It can block access to properties on `window.top`, but my understanding is it won't block access to `window.top` itself. The page you linked to seems to back this up (see Cross-origin script API access). – Aaronius Oct 25 '17 at 03:48
  • @phillyslick in a word: expressiveness. – vhs Dec 21 '18 at 02:07
  • @JoshHabdas `frameElement` will give false-positives if page is embedded into a page on another origin: "returns... null if the element is either top-level or is embedded into a document with a different script origin; that is, in cross-origin situations." https://developer.mozilla.org/en-US/docs/Web/API/Window/frameElement – Skitterm Jun 20 '19 at 19:55
  • 4
    @james-gentes @greg can you explain in which situation `window.self !== window.top` will throw an error? – iamskok Dec 09 '21 at 18:36
  • `window.self` is undefined for me, is this normal? im using latest Firefox. I ended up doing `const isIframe = window !== window.parent` – Noitidart Jun 01 '22 at 06:02
114

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56
  • 4
    Note attempting to read `frameElement` will throw a SecurityError exception in cross-origin iframes, according to [W3C](https://www.w3.org/TR/html5/browsers.html#dom-frameelement) ([WHATWG](https://html.spec.whatwg.org/multipage/browsers.html#dom-frameelement) says it should return null instead). So you might want to wrap it inside a `try...catch` statement. – Oriol Mar 31 '16 at 14:20
  • 15
    getting `null` inside and outside of `iframe` – OlehZiniak Aug 23 '17 at 10:22
  • 8
    The description at [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/frameElement) says that "if the document into which it's embedded has a different origin (such as having been located from a different domain), this is null." – xeophin Jan 08 '18 at 10:40
  • 1
    Just to clerify what the return should be: `Returns the element (such as – Art3mix Dec 07 '18 at 17:12
  • Works like a charm including on same-domain nested iframes. Thanks a lot! – Ivan Jul 24 '21 at 15:17
  • The W3C link seems to be pointing to WHATWG, at least that is how it works now. The error was not thrown, at least not in Firefox. – Pjotr Apr 14 '23 at 12:29
38
if ( window !== window.parent ) 
{
      // The page is in an iframe   
} 
else 
{     
      // The page is not in an iframe   
}
PowerKiKi
  • 4,539
  • 4
  • 39
  • 47
Beweelam
  • 870
  • 9
  • 11
32

I'm not sure how this example works for older Web browsers but I use this for IE, Firefox and Chrome without an issue:

var iFrameDetection = (window === window.parent) ? false : true;
29

RoBorg is correct, but I wanted to add a side note.

In IE7/IE8 when Microsoft added Tabs to their browser they broke one thing that will cause havoc with your JS if you are not careful.

Imagine this page layout:

MainPage.html
  IframedPage1.html   (named "foo")
  IframedPage2.html   (named "bar")
    IframedPage3.html (named "baz")

Now in frame "baz" you click a link (no target, loads in the "baz" frame) it works fine.

If the page that gets loaded, lets call it special.html, uses JS to check if "it" has a parent frame named "bar" it will return true (expected).

Now lets say that the special.html page when it loads, checks the parent frame (for existence and its name, and if it is "bar" it reloads itself in the bar frame. e.g.

if(window.parent && window.parent.name == 'bar'){
  window.parent.location = self.location;
}

So far so good. Now comes the bug.

Lets say instead of clicking on the original link like normal, and loading the special.html page in the "baz" frame, you middle-clicked it or chose to open it in a new Tab.

When that new tab loads (with no parent frames at all!) IE will enter an endless loop of page loading! because IE "copies over" the frame structure in JavaScript such that the new tab DOES have a parent, and that parent HAS the name "bar".

The good news, is that checking:

if(self == top){
  //this returns true!
}

in that new tab does return true, and thus you can test for this odd condition.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
21

The accepted answer didn't work for me inside the content script of a Firefox 6.0 Extension (Addon-SDK 1.0): Firefox executes the content script in each: the top-level window and in all iframes.

Inside the content script I get the following results:

 (window !== window.top) : false 
 (window.self !== window.top) : true

The strange thing about this output is that it's always the same regardless whether the code is run inside an iframe or the top-level window.

On the other hand Google Chrome seems to execute my content script only once within the top-level window, so the above wouldn't work at all.

What finally worked for me in a content script in both browsers is this:

 console.log(window.frames.length + ':' + parent.frames.length);

Without iframes this prints 0:0, in a top-level window containing one frame it prints 1:1, and in the only iframe of a document it prints 0:1.

This allows my extension to determine in both browsers if there are any iframes present, and additionally in Firefox if it is run inside one of the iframes.

magnoz
  • 531
  • 3
  • 11
  • 2
    Try `document.defaultView.self === document.defaultView.top` or `window !== window.top`. In Firefox's add-on SDK's content script, the global `self` object is an object used to communicate with the main script. – Rob W Oct 01 '13 at 21:39
5

I'm using this:

var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
mikewolf78
  • 86
  • 1
  • 2
  • Why do you do this: `.indexOf("HTMLIFrameElement")` ? – Luke Aug 14 '13 at 08:46
  • .indexOf('foobarbaz') > -1 is a way to check for "substring match" (i.e. can 'foobarbaz' be found somewhere within the string?), but without using regular expressions. It's logically equivalent to .match(/foobarbaz/). It (used to:-) work on a wider range of browsers, and still may be used either out of habit or because of fears about the performance of regular expression machinery. – Chuck Kollars Aug 31 '13 at 00:01
3

Best-for-now Legacy Browser Frame Breaking Script

The other solutions did not worked for me. This one works on all browsers:

One way to defend against clickjacking is to include a "frame-breaker" script in each page that should not be framed. The following methodology will prevent a webpage from being framed even in legacy browsers, that do not support the X-Frame-Options-Header.

In the document HEAD element, add the following:

<style id="antiClickjack">body{display:none !important;}</style>

First apply an ID to the style element itself:

<script type="text/javascript">
   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
       antiClickjack.parentNode.removeChild(antiClickjack);
   } else {
       top.location = self.location;
   }
</script>

This way, everything can be in the document HEAD and you only need one method/taglib in your API.

Reference: https://www.codemagi.com/blog/post/194

Community
  • 1
  • 1
Albert Olivé Corbella
  • 4,061
  • 7
  • 48
  • 66
  • 1
    framing is not the only threat, what about objecting (meaning using HTML5 object tag which replaces iframe tag).. i think this will not work against that.. – Raymond Nijland Dec 28 '18 at 17:26
2

I actually used to check window.parent and it worked for me, but lately window is a cyclic object and always has a parent key, iframe or no iframe.

As the comments suggest hard comparing with window.parent works. Not sure if this will work if iframe is exactly the same webpage as parent.

window === window.parent;
Jabran Saeed
  • 5,760
  • 3
  • 21
  • 37
  • in chrome in main window context `window.parent === window` is true. So your answer is incorrect. And this comparsion could be used for check (at least in chrome, didn't test it in another browsers). – MarkosyanArtur Feb 08 '17 at 11:29
  • DOES NOT WORK in context of iFrame, but ` if(window === window.parent){ ` does. *I'm not marking you down as I don't know why it doesn't work* – www-0av-Com Apr 10 '18 at 13:24
2

Use this javascript function as an example on how to accomplish this.

function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe 
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe 
// and the domains are different.
var myresult = true;
try {
    var tophref = top.location.href;
    var tophostname = top.location.hostname.toString();
    var myhref = location.href;
    if (tophref === myhref) {
        myresult = true;
    } else if (tophostname !== "www.yourdomain.com") {
        myresult = false;
    }
} catch (error) { 
  // error is a permission error that top.location.href is not accessible 
  // (which means parent domain <> iframe domain)!
    myresult = false;
}
return myresult;
}
Rolf
  • 398
  • 3
  • 9
1

Since you are asking in the context of a facebook app, you might want to consider detecting this at the server when the initial request is made. Facebook will pass along a bunch of querystring data including the fb_sig_user key if it is called from an iframe.

Since you probably need to check and use this data anyway in your app, use it to determine the the appropriate context to render.

HectorMac
  • 6,073
  • 4
  • 24
  • 24
1
function amiLoadedInIFrame() {
    try {
         // Introduce a new propery in window.top
         window.top.dummyAttribute = true;
         // If window.dummyAttribute is there.. then window and window.top are same intances
         return !window.dummyAttribute;
    } catch(e) {
         // Exception will be raised when the top is in different domain
         return true;
    }
}
Karthikeyan
  • 406
  • 3
  • 14
0

Following on what @magnoz was saying, here is a code implementation of his answer.

constructor() {
    let windowLen = window.frames.length;
    let parentLen = parent.frames.length;

    if (windowLen == 0 && parentLen >= 1) {
        this.isInIframe = true
        console.log('Is in Iframe!')
    } else {
        console.log('Is in main window!')
    }
}
James
  • 699
  • 2
  • 6
  • 23
-2

If you want to know if the user is accessing your app from facebook page tab or canvas check for the Signed Request. If you don't get it, probably the user is not accessing from facebook. To make sure confirm the signed_request fields structure and fields content.

With the php-sdk you can get the Signed Request like this:

$signed_request = $facebook->getSignedRequest();

You can read more about Signed Request here:

https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/

and here:

https://developers.facebook.com/docs/reference/login/signed-request/

Joao Belchior
  • 25
  • 1
  • 6
-2

It's an ancient piece of code that I've used a few times:

if (parent.location.href == self.location.href) {
    window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';
}
  • To add to Eneko Alonso: this works `(parent.location == self.location)` – piotr_cz Aug 20 '13 at 12:21
  • 1
    @piotr_cz, it works only if same-origin policy allows access to `parent.location`. Otherwise an exception is thrown – Dan Jan 13 '14 at 10:50
-3

This ended being the simplest solution for me.

    <p id="demofsdfsdfs"></p>

<script>

if(window.self !== window.top) {

//run this code if in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "in frame";

}else{

//run code if not in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "no frame";
}

</script>
Alex Roseland
  • 461
  • 4
  • 10
-6
if (window.frames.length != parent.frames.length) { page loaded in iframe }

But only if number of iframes differs in your page and page who are loading you in iframe. Make no iframe in your page to have 100% guarantee of result of this code

Vova Popov
  • 1,053
  • 11
  • 11
  • Not a very elegant solution to determining whether or not the window is inside an iframe or not, and there's no guarantee you'll be able to read from parent.frames either. – Percy Sep 22 '15 at 22:27
  • @Percy why not? Isn't `window.frames` is allowed cross origin property? – TheMaster Oct 23 '21 at 16:22
-6

Write this javascript in each page

if (self == top)
  { window.location = "Home.aspx"; }

Then it will automatically redirects to home page.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
shibin
  • 1
  • 1
  • 4
    Your redirect will work when you're not if frame. So I would not be able to navigate in your site. Secondly, techniques exists to prevent from redirecting from the parent page. – Marius Balčytis May 14 '13 at 00:35