iframes aren’t exactly the most widely used browser technology anymore, but that doesn’t meant that they don’t have their place, especially in WordPress development.

For those of you who have worked with features such as the Theme Customizer, then you are certainly familiar with how the feature is structured and the role that an iframe plays in giving you the controls and preview of the theme as you’re making changes.

Although it may not be terribly common, there are times in which you may need to check if a page is in an iframe.

There are a variety of reasons in which this may need to be done (dynamically adjusting the height or width of an element on resize, for example), and it’s really easy to do with a little bit of JavaScript.

Check if a Page Is in an iFrame

In short, to check if a page is in an iframe, you need to compare the object’s location with the window object’s parent location.

If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.

Easy enough, right? So much so that you can run the code within the Chrome Developer Tools, Firebug, or whatever your tool of choice may be, and then see the result directly in the console.

When Would I Use This?

I have no definitive answer for this; however, I’ve used this a couple of times when working on WordPress themes where an element – such as a sidebar – needed to span the height of the document whenever the window was resized or reloaded.

Check if a page is in an iframe

Of course, this will also vary based on the grid, the CSS, and other factors that you have implemented (such as the height of the primary content container).

That said, your mileage and usage may vary based on when you need this; however, this is the most effective way that I’ve found to determine where a page is being viewed.

Category:
Notes
Tags:

Join the conversation! 4 Comments

  1. The main use for this is a frame-breaker.

    if (window != top){
    top.location.href = location.href;
    }

    So pesky sites don’t frame yours.

  2. Or even more simple:

    if ( top !== self ) { // we are in the iframe

    } else { // not an iframe

    }

    It can for example be used for frame busting (preventing anyone to put your website in an iframe):
    if ( top !== self ) top.location.replace( self.location.href );

Leave a Reply