2015-05-12 57 views
0

我在JS中打开新窗口的代码。在加载之前在打开的窗口中添加内容

var myWindow = window.open(); 
myWindow.document.write('html');    

是否有可能在窗口加载之前将文档内容写入文档?我想将整个html添加到文档中,包括一些JS代码。我尝试连接html代码,但即使使用我的代码编辑器也没有完成。

+0

我不认为这是可能的。 –

回答

1

您可以打开之前生成整个文档,但是你做的事情是这样的数据URI或指向斑点对象URL,例如

// Blob method, most modern, almost no restrictions other than legacy browser support 
function genWindow(code) { 
    var b = new Blob([code], {type: 'text/html'}), 
     uri = URL.createObjectURL(b), 
     wind = window.open(uri, '_blank'); 
    URL.revokeObjectURL(uri); // and cleanup 
    return wind; 
} 
genWindow('\ 
<!doctype html>\n\ 
<html>\n\ 
    <head>\n\ 
     <title>Hello World!</title>\n\ 
    </head>\n\ 
    <body>\n\ 
     <span>Foobar</span>\n\ 
    </body>\n\ 
</html>\n\ 
'); 

或者我提到的另一种方法;

// data URI method, more restricted (e.g. file size) but will work in older browsers 
function genWindow2(code) { 
    return window.open('data:text/html,' + window.encodeURIComponent(code), '_blank'); 
} 
genWindow2('\ 
<!doctype html>\n\ 
<html>\n\ 
    <head>\n\ 
     <title>Hello World!</title>\n\ 
    </head>\n\ 
    <body>\n\ 
     <span>Fizzbuzz</span>\n\ 
    </body>\n\ 
</html>\n\ 
'); 
相关问题