2015-05-12 53 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\ 
'); 
相關問題