How to Check a Webpage is Loaded Inside an iframe or 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:

window.self !== window.top

The window.top and window.self are both the objects of window along with parent. The top 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 (self) and with dot notation on a window object (window.self)).

Example:

<!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) {
          // !== the operator checks if the operands are
          // have not the same value or not equal type
          document.write("The page is in loaded in iFrame");
        } else {
          document.write("The page is loaded directly in the browser window.");
        }
      }
      iniFrame();
    </script>
  </body>
</html>

iFrames

iFrame 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> elements, its parent is the window with the element that is embedded in the window.