最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if an element is inside an iframe or not - Stack Overflow

programmeradmin1浏览0评论

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
  • Make a fiddle with your html. – The Alpha 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. – user730569 Commented Sep 9, 2012 at 2:24
  • You want to check the node's existence from the parent page ? – The Alpha 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. – Felix Kling 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. – Felix Kling Commented Sep 9, 2012 at 2:59
 |  Show 8 more comments

3 Answers 3

Reset to default 7

You 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

发布评论

评论列表(0)

  1. 暂无评论