Firefox在每个document.write()之后创建新历史记录的解决方法

Owy*_*wyn 3 firefox document.write

在Firefox中,在每个document.write()都创建了新的历史记录之后,因此,如果在用户按下返回按钮以返回历史记录时在页面加载时调用document.write(),则Firefox将其带至运行document.write()的当前页面)并创建另一个历史记录,因此即使再按一次后退按钮也无济于事,并将他带到他想要的地方

一个简单的解决方法是:

function onbeforeunload(e) 
{
    setTimeout(function() { window.history.go(-2);  }, 0);
}
window.addEventListener("beforeunload", onbeforeunload, true);
Run Code Online (Sandbox Code Playgroud)

但是它不会让用户进入任何链接或在地址栏中键入任何地址然后转到那里,那么还有另一种方法可以修复Firefox吗?

更好的方法是改用onpopstateevent,但在document.write()之后在Firefox中不起作用

不,在这里必须使用document.write()。

Gil*_*ner 5

使用document.open("text/html", "replace")而不是document.open()

奇迹般有效。

有趣的是,其他解决方法无效-例如$('html').replaceWith(pageContent)或在浏览器为Firefox的情况下操纵历史记录...