最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get WHOLE content of iframe? - Stack Overflow

programmeradmin1浏览0评论

I need to get whole content of iframe from the same domain. Whole content means that I want everything starting from <html> (including), not only <body> content. Content is modified after load, so I can't get it once again from server.

I need to get whole content of iframe from the same domain. Whole content means that I want everything starting from <html> (including), not only <body> content. Content is modified after load, so I can't get it once again from server.

Share Improve this question edited Jan 1, 2011 at 18:51 user113716 322k64 gold badges453 silver badges441 bronze badges asked Jan 1, 2011 at 18:47 jesperjesper 8898 silver badges21 bronze badges 2
  • Are you trying to store all resources somewhere in the browser or what are you trying to accomplish? – BastiBen Commented Jan 1, 2011 at 18:51
  • I need to send modified content to server. – jesper Commented Jan 1, 2011 at 19:00
Add a comment  | 

4 Answers 4

Reset to default 19

I belive I've found the best solution:

var document = iframeObject.contentDocument;
var serializer = new XMLSerializer();
var content = serializer.serializeToString(document);

In content we have full iframe content, including DOCTYPE element, which was missing in previous solutions. And in addition this code is very short and clean.

If it is on the same domain, you can just use

iframe.contentWindow.document.documentElement.innerHTML

to get the content of the iframe, except for the <html> and </html> tag, where

iframe = document.getElementById('iframeid');
$('input.test').click(function(){
    $('textarea.test').text($('iframe.test').contents());
});

You can get the literal source of any file on the same domain with Ajax, which does not render the html first-

//

function fetchSource(url, callback){

    try{
        var O= new XMLHttpRequest;
        O.open("GET", url, true);
        O.onreadystatechange= function(){
            if(O.readyState== 4 && O.status== 200){
                callback(O.responseText);
            }
        };
        O.send(null);
    }
    catch(er){}
    return url;
}
function printSourceCode(text){
    var el= document.createElement('textarea');
    el.cols= '80';
    el.rows= '20';
    el.value= text;
    document.body.appendChild(el);
    el.focus();
}

fetchSource(location.href, printSourceCode);

发布评论

评论列表(0)

  1. 暂无评论