Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move the whole document into an iframe

What I'm trying to do is wrap a complete website in an iframe without breaking any styling or javascript.

This is what I've tried:

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

See http://jsfiddle.net/gUJWU/3/

This works fine in Chrome.

Firefox seems to swallow the whole page.

Internet Explorer (see http://jsfiddle.net/gUJWU/3/show/) does create the iframe, doesn't move anything into it.

Does this approach have any chance of working cross-browser?

like image 417
sroes Avatar asked Aug 15 '13 18:08

sroes


1 Answers

In IE, the document isn't inferred and automatically created, so you need to actually create it before accessing it:

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

DEMO: http://jsfiddle.net/XAMTc/show/

This seems to work in IE8/9, and recent Firefox and Chrome, at least.

The way I figured out the problem is by console.logging $frame.contents().find('head').length, which was 0 in IE.

like image 147
Ian Avatar answered Sep 17 '22 02:09

Ian