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?

Cheekysoft
  • 35,194
  • 20
  • 73
  • 86
  • Would you just look for at the parent for frames and see if they exist ? – 76mel May 29 '09 at 08:53
  • Possible duplicate of [How to identify if a webpage is being loaded inside an iframe or directly into the browser window?](http://stackoverflow.com/questions/326069/how-to-identify-if-a-webpage-is-being-loaded-inside-an-iframe-or-directly-into-t) – feeela May 17 '16 at 11:55

5 Answers5

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! */ }
annakata
  • 74,572
  • 17
  • 113
  • 180
12

The predicate

(window.parent.frames.length > 0)

will tell you just what you want.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Artem Barger
  • 40,769
  • 9
  • 59
  • 81
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?

Community
  • 1
  • 1
Mike Grace
  • 16,636
  • 8
  • 59
  • 79
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.

zachberry
  • 97
  • 8
0

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

Ram Sharma
  • 8,676
  • 7
  • 43
  • 56
Pink Duck
  • 561
  • 5
  • 3
  • 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 '13 at 08:38