gpt4 book ai didi

javascript - 在加载之前将内容添加到打开的窗口

转载 作者:行者123 更新时间:2023-12-03 10:09:36 26 4
gpt4 key购买 nike

我在 JS 中打开新窗口的代码。

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

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

最佳答案

您可以在打开文档之前生成整个文档,但这样做的方式是作为数据 URI对象 URL 指向 Blob,例如

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

关于javascript - 在加载之前将内容添加到打开的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30193145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com