[英]How to check if an element is inside an iframe or not
Let's say you have a DOM node and you want to know whether it is located inside an iframe or not.假设您有一个 DOM 节点,并且您想知道它是否位于 iframe 内。 One way would be to check it's parent chain to see if you reached an iframe before reaching the parent window.
一种方法是检查它的父链,看看您是否在到达父 window 之前到达了 iframe。 However, I'd like to know if there is a faster way to do this.
但是,我想知道是否有更快的方法来做到这一点。
You could probably check the ownerDocument
property of the node: 您可以检查节点的
ownerDocument
属性 :
if(node.ownerDocument !== document) {
// node must be inside iframe
}
对我来说最好的方法是const isElementInsideIframe = document.location.ancestorOrigins.length
https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins
Another simple way is:另一种简单的方法是:
const isIframe = window.top !== window.self;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.