4

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
13
  • Make a fiddle with your html. Commented Sep 9, 2012 at 2:23
  • @SheikhHeera That won't help. Just know that I am given a random DOM node from a mutation event, and I want a quick way to know if it is inside an iframe. Commented Sep 9, 2012 at 2:24
  • You want to check the node's existence from the parent page ? Commented Sep 9, 2012 at 2:25
  • 1
    Any events inside iframes are normally not propagated to the parent document, so how can you get a reference to a node inside an iframe (not even speaking of iframes from different domains)? Or do you want to test whether the whole page was loaded into an iframe? Testing the ownerDocument property might work, but it's hard to tell without more information / an example. Commented Sep 9, 2012 at 2:27
  • 1
    @widged: Yeah, the link to the jQuery solution makes sense, but the first two links referring to testing self and top are not useful in this context. Commented Sep 9, 2012 at 2:59

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

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?
You can use document.defaultView and window.frameElement: node.ownerDocument.defaultView.frameElement (doesn't seem to work in IE and below though).
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.
7

Another simple way is:

const isIframe = window.top !== window.self;
answered Aug 22, 2022 at 3:31

Comments

2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.