Check if parent window is iframe or not

岁酱吖の 提交于 2019-12-28 02:29:28

问题


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.


回答1:


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




回答2:


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

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



回答3:


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


来源:https://stackoverflow.com/questions/4594492/check-if-parent-window-is-iframe-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!