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. Here’s a simple function to drop in your code.
As described, if the function returns true
then the page is in an iframe
; otherwise, it’s not.
Easy enough, right? So much so that you can run the code within your browser’s developer tools and see the result 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.
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.
Leave a Reply
You must be logged in to post a comment.