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 code:

Javascript webpage is loaded inside an iFrame

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 iFrame");
        } else {
          document.write("The page is in iFrame");
        }
      }
      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.

iFrame

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.

Do you find this helpful?

Related articles