W3docs

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

Read this JavaScript tutorial and find a working code for checking whether the webpage is loaded inside an iFrame or directly into the browser window.

To check whether a webpage is loaded inside an iframe or directly into the browser window with the help of JavaScript you can use the following conditional statement:

Javascript webpage is loaded inside an iframe

window.self !== window.top

The window.top and window.self are properties of the Window object, along with parent. The top property returns the topmost window in the hierarchy of window objects. It is useful when you deal with a window which is in a subframe of a parent or parents, and you need to get to the top-level frameset.

The window.self is a read-only property that returns the window itself as a WindowProxy. It can be used both standalone (<kbd class="highlighted">self</kbd>) and with dot notation on a window object (<kbd class="highlighted">window.self</kbd>).

Example:

Javascript webpage is loaded inside an iframe

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <script>
      // Function to check if a webpage is in iframe
      function inIframe() {
        if(window.self !== window.top) {
          // !== operator checks if the operands do not have the same value or type
          console.log("The page is loaded in an iframe");
        } else {
          console.log("The page is loaded directly in the browser window.");
        }
      }
      inIframe();
    </script>
  </body>
</html>

iframe

<kbd class="highlighted">iframe</kbd> is a rectangular frame in the webpage used for loading or displaying another separate webpage or document inside. It is used to display a webpage within a webpage.

The window.parent property is a reference to the parent of the window or subframe. If the window is parentless, the parent property becomes a reference to itself. If a window is loaded in an <iframe>, <frame>, or <object> element, its parent is the window with the element that is embedded in the window.