Getting Iframe content in Javascript


Iframe is an inline frames, allow you to load the separate html file into an existing document. You can also load the file dynamically with “src” attribute. Suppose there is a need to get the iframe content and process it using javascript. The following example helps you to do it and this has been a cross browser solutions for Firefox & IE browsers.
Let’s load a simple html file inside the iframe, and get that file content with javascript method getIframeContent.

GetIframeDetails.html


<html>
 <body>
 <iframe id="testFrame" src="FrameContent.html" >
 </iframe>
<a href="#" onclick="getIframeContent('testFrame');">Get the content of Iframe</a>
 </body>
<script>
 function getIframeContent(frameId){
 var frameObj = document.getElementById(frameId);
 var frameContent = frameObj.contentWindow.document.body.innerHTML;
 alert("frame content : "+frameContent);
 }
 </script>
 </html>
 

FrameContent.html


<html><body>
 <div id="testFrameContent" style="border:1px;">
 This is simple HTML file which is loaded inside the iframe.
 </div>
 </body>
 </html>

what getIframeContent method do?


function getIframeContent(frameId){
 var frameObj = document.getElementById(frameId);
 var frameContent = frameObj.contentWindow.document.body.innerHTML;
 alert("frame content : "+frameContent);
 }

  • getElementById(frameId) – get the object reference of iframe
  • contentWindow – is a property which returns the window object of the iframe
  • contentWindow.document – returns the document object of iframe window.
  • contentWindow.document.body.innerHTML – returns the HTML content of iframe body.

You can also access any tag element’s inside the iframe. This can be done by processing with tag names/ids. Let’s imagine the use case: to retrieve the content of div element inside the iframe. Below statement will retrieve it.

frameObj.contentWindow.document.getElementById(“testFrameContent”).innerHTML

Blogs about dynamically change the iframe heights.

https://manikandanmv.wordpress.com/2009/05/25/version-2-dynamically-change-iframe-heights/
https://manikandanmv.wordpress.com/2009/04/25/dynamically-change-iframe-heights/

Advertisements

Tags: , , , , , , , ,

One Response to “Getting Iframe content in Javascript”

  1. Baris AKDEMIR Says:

    I’m search this code 3 hours and finally find working code. You are hero of this night šŸ™‚ Thanks you so much.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: