Archive for November, 2009

Getting Iframe content in Javascript

November 6, 2009

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