简体   繁体   English

如何获得iframe的全部内容?

[英]How to get WHOLE content of iframe?

I need to get whole content of iframe from the same domain. 我需要从同一个域获取iframe的全部内容。 Whole content means that I want everything starting from <html> (including), not only <body> content. 整个内容意味着我希望一切都从<html> (包括)开始,而不仅仅是<body>内容。 Content is modified after load, so I can't get it once again from server. 内容在加载后被修改,因此我无法再从服务器获取它。

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. content我们有完整的iframe内容,包括DOCTYPE元素,这在以前的解决方案中是缺失的。 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的内容,除了<html></html>标签,其中

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- 您可以使用Ajax获取同一域上任何文件的文字源,这不会首先呈现html-

// //

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); fetchSource(location.href,printSourceCode);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM