59

I have an application that has a certain page -- let's call it Page A. Page A is sometimes a top-level page, but also sometimes is embedded as an iframe within page B. All pages come from the same server and there are no cross-domain issues.

I have a greasemonkey script that runs on page A. How can the greasemonkey script detect whether page A is within the iframe context or not?

2

5 Answers 5

134

Looking at frame length breaks down generally if page A itself has frames (I know this might not be the case for this specific instance). The more reliable and meaningful test would be:

if (window!=window.top) { /* I'm in a frame! */ }
4
  • Can you explain? Is this because a.parent can equal a?
    – Cheekysoft
    May 29, 2009 at 9:33
  • 6
    yes, exactly so - .top and .parent can point to the same object as .self (and in fact it would possibly be clearer to test window.self != window.top)
    – annakata
    May 29, 2009 at 9:59
  • This didn't work for me inside a Firefox extension, but I found a different solution: stackoverflow.com/questions/326069#7769187
    – magnoz
    Oct 14, 2011 at 14:39
  • I confirm, for covering also IE8 you have to use window.parent.frames.length Dec 14, 2012 at 10:49
12

The predicate

(window.parent.frames.length > 0)

will tell you just what you want.

3
  • 1
    Just don't forget to do it after ;0) May 29, 2009 at 9:10
  • 3
    This approach gives you false positive if you nest another iframe on the page you run this check on. Apr 25, 2013 at 10:07
  • 1
    this is not that simple. if your page contains iframes, than window.parent == window so it would give false positive.
    – zsitro
    Nov 8, 2013 at 14:52
6
if (top === self) { not in a frame } else { in a frame }

From How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

4

As stated above the accepted solution doesn't work in IE8. Additionally, checking window.parent.frames.length can cause a cross-domain exception.

Instead I was able to achieve this with var isInIFrame = top.location != self.location - it works in IE8 and it doesn't cause a cross-domain violation as long as you don't attempt to read the contents of top.location.

0

Use window.frameElement and check if it is not null and if its nodeName is "IFRAME".

1
  • 1
    This element is not available in Safari or Opera. Given the number of people surfing on iPads these days, this probably isn't a suitable solution.
    – Ash
    Nov 28, 2013 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.