Check if a page is loaded in an iframe using Javascript

|
I am across this solution today after some head scratching. The solution turned out to be quite simple. To do the check just use the follow code:

var isInIFrame = (window.location != window.parent.location) ? true : false;
And that is it. This will work for all cases as long as your are not loading a page in an iframe of it self, which may possibly cause an infinite loop, you are fine. I have tested this in Firefox 3, Chrome 1.x and Internet Explorer 7.

7 comments:

Greg said...

Wow, just needed this and ran across it. Thanks! Just out of curiosity, have you tried it across subdomains (setting document.domain) in various browsers?

mcg said...

Works like a charm. Thank you!

theY4Kman said...

Thanks for this. Found it right when I needed it!

4fun1ly said...

your code just compares page url of iFrame with parent page url, but not page successfully loaded or not. So, you can't assume page is loaded or not.

Sfate said...

you can also just use:
var isInIFrame = (window.location != window.parent.location)

Ankit said...

not working in IE, in rest all browser it works

Bas said...

If you want to detect a specific iframe, then give it a name and detect using javascript, for example:

..iframe src="http://foobar.com" name="intranet"..

.. (iframe website code) ..
if (window.name == "intranet") {
...
}

Post a Comment