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.
asked Sep 9, 2012 at 2:19
user730569
4,0069 gold badges45 silver badges68 bronze badges
3 Answers 3
You could probably check the ownerDocument property of the node:
if(node.ownerDocument !== document) {
// node must be inside iframe
}
answered Sep 9, 2012 at 2:42
Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
user730569
thanks, is there also a fast way to get a reference of the iframe it is inside, or do I need to iterate through all iframes?
Felix Kling
You can use
document.defaultView and window.frameElement: node.ownerDocument.defaultView.frameElement (doesn't seem to work in IE and below though).KenneyE
Unfortunately, this won't work if the script you are running is also in an iFrame. This will only indicate whether or not the element is in the same document as the script.
Another simple way is:
const isIframe = window.top !== window.self;
answered Aug 22, 2022 at 3:31
Prince Ahmed
1,13812 silver badges10 bronze badges
Comments
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
answered Oct 14, 2021 at 19:09
Eugene Godun
3763 silver badges5 bronze badges
Comments
default
ownerDocumentproperty might work, but it's hard to tell without more information / an example.selfandtopare not useful in this context.