如何检查元素是否在iframe中

How to check if an element is inside an iframe or not

本文关键字:是否 iframe 元素 何检查 检查      更新时间:2023-09-26

假设您有一个DOM节点,您想知道它是否位于iframe中。一种方法是检查它的父链,看看你是否在到达父窗口之前到达了iframe。不过,我想知道是否有更快的方法。

您可能会检查节点的ownerDocument属性:

if(node.ownerDocument !== document) {
    // node must be inside iframe
}

对我来说最好的方法是const isElementInsideIframe = document.location.ancestorOrigins.lengthhttps://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins

另一种简单的方法是:

const isIframe = window.top !== window.self;