无法在 Firefox 中设置新的"about:blank"-window 的 body.innerHTML (window.open())



这是一个问答风格的线程,因为我找不到有这个问题/有解决方案的人。

箱:

你有一个javascript,你打开一个新窗口,用window.open('about:blank', ...)打开一个新窗口,你想通过设置myWindowReference.document.body.innerHTML = SOMETHING来设置它的内容。

问题:

在Chrome,Edge,IE,Opera中运行良好,但在Firefox的几个(也许是所有?)版本中不能正常工作。页面保持白色,但console.dir(myWindowReference.document.body.innerHTML);的日志消息是正确的。

示例代码:

<!doctype html>
<html>
<head>
<script>
window.onload = () => {
let wind = window.open('about:blank', 'someName', 'resizable,scrollbars');
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
wind.focus();
console.log("wind.document.body.innerHTML:");
// OUTPUT IS CORRECT
// but page is blank
console.dir(wind.document.body.innerHTML);
}
</script>
</head>
<body></body>
</html>

解决方案

我的猜测是,Firefox 不会在内部等待窗口引用完全存在,因此不会更新 GUI,而是在内部以某种方式更新它,以便console.dir(wind.document.body.innerHTML);无论如何都有正确的输出。我发现一个解决方案正在使用超时,以便 Firefox 有足够的时间在内部完全构建窗口引用。

<!doctype html>
<html>
<head>
<script>
window.onload = () => {
let wind = window.open('about:blank', 'someName', 'resizable,scrollbars');
// [B] DOES WORK
window.setTimeout(() => {
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
}, 1)  // USING A TIMEOUT IS THE SOLUTION
/* [A] DOESN't WORK
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
*/
wind.focus();
console.log("wind.document.body.innerHTML:");
console.dir(wind.document.body.innerHTML);
/*
This log message is in either way ([A] and [B]) correct in Firefox.
With [A] there is no content and no title set to the window, althrough it is visible.
With [B] it works. Seems like Firefox is internally not waiting for the right reference/
until the window is opened.
*/
}
</script>
</head>
<body></body>
</html>

解决方案2(更好的解决方案):

发现没有必要在window.open()中使用"about:blank"来表示空页面。因为"about:blank"是Firefox中的一个特殊页面,这可能是错误的原因。只需将其留空即可工作。

<!doctype html>
<html>
<head>
<script>
window.onload = () => {
let wind = window.open('', 'someName', 'resizable,scrollbars');
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
wind.focus();
}
</script>
</head>
<body></body>
</html>

最新更新