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

长平狐 发布于 2013/01/06 11:21
阅读 122
收藏 0

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

http://roneiv.wordpress.com/2008/01/18/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 pre 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   

}

 

 

 

 

 

 

 

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2512479次
    • 积分:22821分
    • 排名:第57名
    • 原创:349篇
    • 转载:210篇
    • 译文:10篇
    • 评论:1307条
    工作经历
    中科院、百度、六所、创新工场

    博客专栏
    博客公告
    本博客内容,由本人精心整理

    欢迎交流,欢迎转载,大家转载请注明出处,禁止用于商业目的

    文章分类
pre
原文链接:http://blog.csdn.net/sunboy_2050/article/details/5876146
加载中
返回顶部
顶部