javascript - 将整个文档移动到 iframe 中

标签 javascript iframe

我想做的是在不破坏任何样式或 javascript 的情况下将完整的网站包装在 iframe 中。

这是我试过的:

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.logging $frame.contents().find('head').length,它在 0浏览器。

关于javascript - 将整个文档移动到 iframe 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259499/

相关文章:

javascript - QUnit 设置回调在 Internet Explorer 9 中运行任何测试之前调用的所有内容

javascript - JS/JQuery 获取多维对象中键的值

javascript - Nodejs Mongoose : Trying to save date in UTC Timezone but its saving in local time zone

javascript - 从数据库加载 iframe

javascript - 从 iframe 到 iframe 的访问 - Angular 场景

javascript - 使用 Node 解析 XLSX 并创建 json

javascript - 以前点击的项目被模态删除

testing - 与具有空 src 属性的 iframe 交互

javascript - 拦截iframe消息嵌套iframe,跨域

javascript - ASP :LinkButton doesn't work from inside an iframe