Let's say you have a DOM node and you want to know whether it is located inside an iframe or not. One way would be to check it's parent chain to see if you reached an iframe before reaching the parent window. However, I'd like to know if there is a faster way to do this.
Let's say you have a DOM node and you want to know whether it is located inside an iframe or not. One way would be to check it's parent chain to see if you reached an iframe before reaching the parent window. However, I'd like to know if there is a faster way to do this.
Share Improve this question asked Sep 9, 2012 at 2:19 user730569user730569 4,0049 gold badges44 silver badges68 bronze badges 13 | Show 8 more comments3 Answers
Reset to default 7You could probably check the ownerDocument
property of the node:
if(node.ownerDocument !== document) {
// node must be inside iframe
}
Another simple way is:
const isIframe = window.top !== window.self;
The best way that works for me is
const isElementInsideIframe = document.location.ancestorOrigins.length
https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins
ownerDocument
property might work, but it's hard to tell without more information / an example. – Felix Kling Commented Sep 9, 2012 at 2:27self
andtop
are not useful in this context. – Felix Kling Commented Sep 9, 2012 at 2:59