将整个文档移动到iframe中

Move the whole document into an iframe

本文关键字:iframe 移动 文档      更新时间:2023-09-26

我想做的是将一个完整的网站包装在iframe中,而不破坏任何样式或javascript。

这就是我尝试过的:

var $frame = $('<iframe />').css({
    position: 'fixed',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%'
}).appendTo('body');
$('head').children().appendTo($frame.contents().find('head'));
$('body').children().not($frame).appendTo($frame.contents().find('body'));

请参阅http://jsfiddle.net/gUJWU/3/

这在Chrome中运行良好。

Firefox似乎吞噬了整个页面。

Internet Explorer(请参阅http://jsfiddle.net/gUJWU/3/show/)确实创建了iframe,没有向其中移动任何内容。

这种方法有可能跨浏览器工作吗?

在IE中,文档不是推断和自动创建的,因此您需要在访问它之前实际创建它:

var $frame = $('<iframe />').css({
    position: 'fixed',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%'
}).appendTo('body');
var doc = $frame[0].contentDocument || $frame[0].contentWindow.document;
doc.open();
doc.write("<!DOCTYPE html><html><head><title></title></head><body></body></html>");
doc.close();
$('head').children().appendTo($frame.contents().find('head'));
$('body').children().not($frame).appendTo($frame.contents().find('body'));

演示:http://jsfiddle.net/XAMTc/show/

这似乎适用于IE8/9,以及最近的Firefox和Chrome。

我解决问题的方法是通过console.log对IE中为0的$frame.contents().find('head').length进行更新。