Get the content of an Iframe in Javascript – crossbrowser solution for both IE and Firefox

Ok, let’s imagine the use case: I have an iframe somewhere on my page, and when I click a link or a button I need to get the content of it (could be a textarea e.g.), and then do some stuff with it.

It was easy to do this in IE, but for Firefox I struggled more, as I kept getting the “frame has no properties” error message in the console. And when I solved this I couldn’t get to the content.

There is a lot of references out there claiming that you could use document.frames[‘nameOfMyIframe’] or window.frames[‘nameOfMyIframe’] to get the frame, and then use the .innerHTML to get the content, but both are wrong.

I came up with the following function that seems to do the job in both Firefox (tested on version 2.0.0.11 and 3.03 ) and in IE (6 and 7):


function getContentFromIframe(iFrameName)
{

    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;

    //Do whatever you need with the content    

}

This wasn’t my biggest contribution, but I spent some time trying to find this solution, and for some of you it might be helpful saving you frome some heavy googling.

Because of some postings about people struggling to get this to work, I now include an example using this script. The example consist of two files, main.html and frame.html. If you want to try it locally, put both of them in the same folder and open main.html.

Main.html:

<html>
<head>

</head>
<body>
<script type="text/javascript">
function getContentFromIframe(iFrameName)
{

    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;

    alert('content: ' + content);    

    content = 'The inside of my frame has now changed';
    myIFrame.contentWindow.document.body.innerHTML = content;

}

</script>



</iframe>

<a href="#" onclick="getContentFromIframe('myIframe')">Get the content</a>

</body>

</html>

Frame.html:

<html>
<head>

</head>
<body>

This is inside my frame
</body>

</html>
Advertisements