How to Check a Webpage is Loaded Inside an iframe or into the Browser Window

When developing a website, you may need to check if a certain page is loaded inside an iframe or directly in the browser window.

This information can be used to implement different behaviors and styles for different scenarios.

In this Javascript tutorial, we will discuss how to determine if a webpage is loaded inside an iframe or directly in the browser window.


Methods to check if a webpage is loaded in an iframe

window.frameElement property

The window.frameElement property returns the iframe element that contains the current window, or null if the current window is not contained in an iframe.

You can use this property to check if a webpage is loaded inside an iframe.

Example:

if (window.frameElement) {
  console.log("The current window is inside an iframe.");
} else {
  console.log("The current window is not inside an iframe.");
}

window.self and window.top properties

The window.self property refers to the current window and the window.top property refers to the top-level window.

If the current window is not contained in an iframe, window.self and window.top will be the same.

If the current window is contained in an iframe, window.self will be the current window and window.top will be the top-level window.

Example:

if (window.self === window.top) {
  console.log("The current window is not inside an iframe.");
} else {
  console.log("The current window is inside an iframe.");
}

Conclusion

In conclusion, you can use either the window.frameElement property or the window.self and window.top properties to determine if a webpage is loaded inside an iframe or directly in the browser window.

Depending on your specific requirements, you can choose the most appropriate method and implement it in your website.