How to get WHOLE content of iframe?

2019-02-13 23:21发布

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.

4条回答
何必那么认真
2楼-- · 2019-02-13 23:38

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');
查看更多
等我变得足够好
3楼-- · 2019-02-13 23:49
$('input.test').click(function(){
    $('textarea.test').text($('iframe.test').contents());
});
查看更多
爷、活的狠高调
4楼-- · 2019-02-13 23:56

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-02-13 23:56

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);

查看更多
登录 后发表回答