Check if parent window is iframe or not

JavascriptJqueryIframe

Javascript Problem Overview


How can I tell from a page within an iframe, if the parent itself is also within an iframe?

Explanation:

My home page home.html contains an iframe

<iframe src="sample.html"></iframe>

I need to detect if home.html (ie: parent of sample.html) is within an iframe.

Code in sample.html:

if(self==window)
{
    alert('home.html is not in iframe');
}
else
{
    alert('home.html is in iframe');
}

My question is not a duplicate. It's a different case.

Javascript Solutions


Solution 1 - Javascript

This is true if a window is not a frame/iframe:

if(self==top)

If you like to see if the parent window of the given window is a frame, use:

if(parent==top)

It's a simple comparision of top (the most top window of the window hierarchy) and another window object (self or parent).

Solution 2 - Javascript

Check if window.frameElement is not null and see if its nodeName property is "IFRAME":

var isInIframe = window.frameElement && window.frameElement.nodeName == "IFRAME";

Solution 3 - Javascript

var isInIFrame = (window.location != window.parent.location);
if(isInIFrame==true){
    // iframe
}
else {
    // no iframe
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohan RamView Question on Stackoverflow
Solution 1 - JavascriptDr.MolleView Answer on Stackoverflow
Solution 2 - JavascriptPink DuckView Answer on Stackoverflow
Solution 3 - JavascriptSumith HarshanView Answer on Stackoverflow