Javascript 检查父窗口是否为 iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4594492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:08:54  来源:igfitidea点击:

Check if parent window is iframe or not

javascriptjqueryiframe

提问by Mohan Ram

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

如果父级本身也在 iframe 中,如何从 iframe 中的页面判断?

Explanation:

解释:

My home page home.htmlcontains an iframe

我的主页home.html包含一个 iframe

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

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

我需要检测home.html(即:的父级sample.html)是否在 iframe 内。

Code in sample.html:

代码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.

我的问题不是重复的。这是一个不同的案例。

回答by Dr.Molle

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

如果窗口不是框架/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 (selfor parent).

这是top(窗口层次结构的最顶层窗口)和另一个窗口对象(selfparent)的简单比较。

回答by Pink Duck

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

检查是否window.frameElement不为空并查看其 nodeName 属性是否为“IFRAME”:

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

回答by Sumith Harshan

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