Check if parent window is iframe or not

2019-01-08 09:30发布

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.

3条回答
别忘想泡老子
2楼-- · 2019-01-08 09:33

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).

查看更多
何必那么认真
3楼-- · 2019-01-08 09:54

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

var isInIframe = window.frameElement && window.frameElement.nodeName == "IFRAME";
查看更多
贪生不怕死
4楼-- · 2019-01-08 09:57
var isInIFrame = (window.location != window.parent.location);
if(isInIFrame==true){
    // iframe
}
else {
    // no iframe
}
查看更多
登录 后发表回答