Open In App

How to get HTML content of an iFrame using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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) {
let frameObj =
document.getElementById(frameId);
let 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 that returns the window object of the iframe.
  • contentWindow.document: It returns the document object of the iframe window.
  • contentWindow.document.body.innerHTML: It returns the HTML content of the iframe body.

Example: The following example demonstrates to inclusion of separate HTML files into existing documents.

html




<!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) {
            let frameObj =
                document.getElementById(frameID);
            let frameContent = frameObj
                .contentWindow.document.body.innerHTML;
 
            alert("frame content : " + frameContent);
        }
    </script>
</body>
 
</html>


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

html




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


Output:

ezgifcom-video-to-gif-converted-(1)

Output



Last Updated : 15 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads