How to get the body's content of an iframe in JavaScript?


We use getIframeContent(frameId), to get the object reference of an iframe in JavaScript.

To get the element in an iframe, first we need access the <iframe> element inside the JavaScript using the document.getElementById() method by passing iframe id as an argument.

Using iframetag

The <iframe> tag in HTML specifies an inline frame. This inline frame is used to embed another document within the current HTML document.

The <iframe> element is supported in every browser like (Google Chrome, Microsoft edge/ internet explorer, Firefox, safari, and opera).

We are using srcdoc attribute in <iframe> tag to specify the HTML content of the page to show in the <iframe>.

The attribute srcdoc will take HTML_code as a value and specifies the HTML content of the page to show in the <iframe>.

Following are the examples where we used the <iframe> tag with srcdoc attribute to specify the HTML content of the page to show in the <iframe> in HTML.

Now let’s look into the examples one by one.

Example

Following is the example program to create a window using iframe.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <iframe id = "myId" name = " myId ">...</iframe> <script> var myDoc; if (window.frames && window.frames. myId && (myDoc = window.frames. myId.document)) { var iframeBody = myDoc.body; var content = iframeBody.innerHTML; } </script> </body> </html>

Example

Following is the example program to place a content on the window created by iframe.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> How to get HTML content of an iFrame using javascript? </title> </head> <body> <iframe id="frameID" src="Untitled-2.html"> </iframe> <a href="#" onclick= "getIframeContent('frameID');"> Get 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>

Undefined.html

<!DOCTYPE html> <html> <body> got the body's content of an iframe in JavaScript </body> </html>

After clicking on the get content a pop-up window will show the content of the iframe.

Updated on: 21-Nov-2022

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements