I hit a JavaScript issue recently that stumped me. I’m trying to detect if the code I’m running is in an IFrame or not. It seems like the safest way to determine this would be the following comparison:

if(window !== top) {
   var mode = "frame";
}

‘window’ of course is the global object in which your code is running. If you’re running in a frame, your window object is actually a child in a window hierarchy. ‘top’ refers the to the top-most window in the hierarchy. Therefore if window and top are the same, then you are in a top level page; conversely if they are different, then you are in a frame (or iframe).

This works great on Firefox but on IE, the window !== top expression never evaluates to true. That is, even if you’re the top window, ‘top’ and ‘window’ aren’t considered equal. I’m not sure why this is. My current fallback code is this:

try {
    if (top.location.href !== window.location.href) {
        var mode = "frame";
    }
} catch (e) {    
    // if you're in an iframe in a different domain, the top.location check
    // results in a security exception
    mode = "frame";
}

This code has two problems:

  1. There’s a small possibility that you could have the a frame with the same URL as the outer page. This is very unlikely because there’s no scenario I know of where you want to nest a page, but it’s still a latent bug.
  2. You have to deal with the exception in the cross domain case. Not a big deal but unclean.

I’m curious if anyone has a better solution for detecting whether or not you’re in an IFrame.