google-chrome - onpopstate 处理程序不会在 Chrome 中触发,除非在点击后退按钮之前发生鼠标单击

标签 google-chrome dom-events

我最近偶然发现了 OSX 上 Chrome 的奇怪行为。加载某个页面时,我会将一个新页面推送到窗口历史记录中,这样如果用户单击后退按钮,则会加载新页面,而不是刚刚来自的页面。

我正在使用 replaceStatepushState 修改历史记录,并设置 onpopstate 处理程序以在后退按钮时加载新页面被点击。

但是,在 Chrome 中,这不起作用,除非用户在单击后退按钮之前单击页面上的任意位置(或按任意键)。

我似乎无法在 fiddle 上演示这个,但是如果您设置以下内容,您应该能够重现该行为

page1.html

<html>
<body>
<h1>This is page 1</h1>
<a href="page3.html">Go to page 3</a>
</body>
</html>

page2.html

<html>
<body>
<h1>This is page 2</h1>
<p>Well, how did you get here?</p>
</body>
</html>

page3.html

<html>
<body>
<h1>This is page 3</h1>
<p>Why don't you go back to page 1?</p>
<script>
history.replaceState(null, '', 'page2.html');
history.pushState(null, '', 'page3.html');
window.onpopstate = function(event) {
  console.log("Reloading page in onpopstate handler");
  window.location = document.location
}
console.log("Push page2.html to history");
</script>
</body>
</html>

然后在同一目录中启动简单的网络服务器(例如,python -m SimpleHTTPServer 8000)并在 Chrome 中打开 localhost:8000/page1.html

我希望您应该能够单击指向第 3 页的链接,然后立即单击后退按钮并最终到达第 2 页。但是您没有,最终返回到第 1 页。

但是,如果您单击指向第 3 页的链接,然后单击页面上的任意位置,然后单击后退按钮,您将按预期到达第 2 页。在单击后退按钮之前按任意键也可以。

在 Firefox 和 Safari 中,您总是会按预期到达第 2 页。

我运行的是 OSX 10.14.5 和 Chrome 75.0.3770.100。

最佳答案

Chrome 75启动了历史记录操纵干预。

Here是公告/更多详细信息。

干预摘要:

Some pages make it difficult or impossible for the user to go back to the page they came from via the browser back button. This is accomplished by redirects or by manipulating the browser history and results in an abusive/annoying user experience. This intervention makes the browser's back button consistent and prevents abuse. The new behavior of the browser’s back button will be to skip over pages that added history entries or redirected the user without ever getting a user gesture. Note that the intervention only impacts the browser back/forward button UI and not the history.back/forward APIs.

在此特定示例中,按返回键后,用户将转到他们访问的最后一个页面(第 1 页),而不是新页面。这符合用户对浏览器后退按钮的期望。

关于google-chrome - onpopstate 处理程序不会在 Chrome 中触发,除非在点击后退按钮之前发生鼠标单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56908215/

相关文章:

javascript - Google Chrome Object.defineProperty 中的错误行为?

html - 奇怪的 CSS 问题 - 在 Safari 上运行正常,在 Chrome 上运行不正常

google-chrome - watir-webdriver 是否有 watir::ie.attach 的替代方案,因为 webdriver 不支持附加

google-chrome - Chrome 开发者工具在 Mac 上被禁用

javascript - 如何插入脚本标签并通过src执行响应?

javascript - 事件—— 'mouseup' 鼠标移动后未触发

javascript - 如果安装了插件,如何检查 Firefox 和 Chrome

javascript - 检测对给定 JavaScript 事件的支持?

JavaScript 鼠标悬停在子对象上方时触发

javascript - 当脚本在主体树中执行时,DOM 准备好了吗?