How to get HTML content of an iFrame using JavaScript ?

The <iframe> tag specifies an inline frame. It allows us to load a separate HTML file into an existing document.

Code snippet:

function getIframeContent(frameId) {
    var frameObj = 
        document.getElementById(frameId);

    var frameContent = frameObj.
        contentWindow.document.body.innerHTML;
        
    alert("frame content : " + frameContent);
}

Some of the definitions are given below:

  • getIframeContent(frameId): It is used to get the object reference of an iframe.
  • contentWindow: It is a property which returns the window object of the iframe.
  • contentWindow.document: It returns the document object of iframe window.
  • contentWindow.document.body.innerHTML: It returns the HTML content of iframe body.

Example: The following example demonstrates to include separate HTML file into existing document.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to get HTML content of 
        an iFrame using javascript?
    </title>
</head>
  
<body>
    <iframe id="frameID" src=
        "ContentOfFrame.html">
    </iframe>
  
    <a href="#" onclick=
        "getIframeContent('frameID');">
        Get the content of Iframe
    </a>
  
    <script>
        function getIframeContent(frameID) {
            var frameObj = 
                document.getElementById(frameID);
            var frameContent = frameObj
                .contentWindow.document.body.innerHTML;
  
            alert("frame content : " + frameContent);
        }
    </script>
</body>
  
</html>

chevron_right


ContentOfFrame.html The following example demonstrates the HTML code content of file “ContentOfFrame.html”

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body>
    GeeksForGeeks: A Computer 
    Science Portal For Geeks
    (It is loaded inside the 
    iframe)
</body>
  
</html>

chevron_right


Output:

  • Before clicking the link:
  • After clicking the link:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.