Explain Codes LogoExplain Codes Logo

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

javascript
iframe-detection
cross-origin-restrictions
same-origin-policy
Anton ShumikhinbyAnton Shumikhin·Jan 15, 2025
TLDR

Here's an instant solution for detecting whether a webpage is in an iframe using JavaScript:

const isInIframe = window !== window.parent;

The variable isInIframe is true if your page is inside an iframe, and false if it's directly loaded in the browser window.

It doesn't stop here though. Let's make it cross-origin friendly and delve into further aspects of this topic in a more comprehensive manner.

Cross-origin restrictions and iframe detection

In today's reality of the web, cross-origin restrictions can pose a challenge with iframes. When your iframe and the parent document originate from different domains, access to objects such as window.parent could be blocked due to the browser's Same-Origin Policy. Here's the workaround:

let isInIframe; try { isInIframe = window.self !== window.top; } catch (e) { isInIframe = true; // Whoops! Access denied, but we still know we are in an iframe. }

This robust check will safeguard your code from unexpected exceptions due to cross-origin restrictions.

Using frameElement for iframe detection

We can rely on the window.frameElement, and it is null when the current window is NOT an iframe. Here's how to check:

const isInIframe = window.frameElement != null;

Just remember that you may get an error if the iframe resides on a different domain, courtesy again of the cross-origin restrictions!

Making your application iframe-friendly

While creating applications that can function both in a standalone window or an iframe, there are a few important points to consider:

  • User Experience: When in an iframe, some adjustments to the layout or navigation may be necessary.
  • Functionality: Certain operations require full window access. Knowing the context helps in managing those functionalities.
  • Performance: There might be performance challenges running an app inside an iframe due to limited resources.

Adapting app behavior based on loading context

Your application may need to behave differently based on the loading context. Here's a sneak peek at what that might look like:

if (window !== window.parent) { // Oops! We're in an iframe. Let's make some adjustments. adaptToIframe(); } else { // Aha! Loaded directly in a browser. Time to stretch out. adaptToDirectLoad(); }

This is particularly important if your apps are being served on platforms like the Facebook canvas.