JavaScript 如何检查网页是否在iframe中加载或在浏览器窗口中加载
iFrame 是网页中用于加载或显示另一个独立网页或文档的矩形框架或区域。基本上,iFrame用于在网页内显示另一个网页。你可以在这里了解更多关于 iFrames 的信息:HTML iFrames。检查网页是否在iFrame中加载的原因可能有很多,例如在需要动态调整元素的高度或宽度的情况下。
将对象的位置与窗口对象的父级位置进行比较:** 在这种情况下,我们只需将对象的位置与窗口对象的父级位置进行比较。如果结果为true,则网页在iFrame中。如果结果为false,则网页不在iFrame中。
<script>
function iniFrame() {
if ( window.location !== window.parent.location )
{
// The page is in an iFrames
document.write("The page is in an iFrame");
}
else {
// The page is not in an iFrame
document.write("The page is not in an iFrame");
}
}
// Calling iniFrame function
iniFrame();
</script>
输出:
The page is in an iFrame
使用window.top和window.self属性:** top和self都是window对象,连同parent一起,因此检查当前窗口是否为顶级/主窗口。
<script>
// Function to check whether webpage is in iFrame
function iniFrame() {
if(window.self !== window.top) {
// !== operator checks whether the operands
// are of not equal value or not equal type
document.write("The page is in an iFrame");
}
else {
document.write("The page is not in an iFrame");
}
}
// Calling iniFrame function
iniFrame();
</script>
输出:
The page is in an iFrame
使用window.frameElement属性:** 请注意,此方法仅支持与嵌入它的主页面具有相同源的网页。函数 window.frameElement 返回所嵌入网页的元素(如iframe和object)。
<script>
function iniFrame() {
var gfg = window.frameElement;
// Checking if webpage is embedded
if (gfg) {
// The page is in an iFrame
document.write("The page is in an iFrame");
}
else {
// The page is not in an iFrame
document.write("The page is not in an iFrame");
}
}
// Calling iniFrame function
iniFrame();
</script>
输出:
The page is in an iFrame
- 在上述代码中,将包含网页的元素存储到变量 gfg 中。如果窗口没有嵌入到另一个文档中,或者嵌入的文档具有不同的源(比如来自于不同的域), gfg 的值为空。
极客教程