html - history.pushState 不触发 'popstate' 事件

标签 html history.js

为什么

window.addEventListener('popstate', () => alert('pop'));

window.history.pushState(null, '', '/foo');

不提醒 pop ?

注意:在最新的 chrome 上测试

--

根据 MDN :

A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to pushState or affected by a call to replaceState, the popstate event's state property contains a copy of the history entry's state object.

那么为什么我的pushState 没有触发popstate 事件呢?

最佳答案

您可以在每次调用history.pushState()时手动触发window上的popstate事件。

history.pushState(state, '', url);

var popStateEvent = new PopStateEvent('popstate', { state: state });
dispatchEvent(popStateEvent);

关于html - history.pushState 不触发 'popstate' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10940837/

相关文章:

javascript - HTML5 History.pushState 破坏包含百分比编码的非 Ascii (Unicode) 字符的 URL

javascript - 简单的 jquery 无法打印输入值

php - 单击按钮时在输入字段中显示文本(php/html)

jquery - 全屏部分的 History.js

javascript - react /Node 构建错误。找不到模块 'history' 的声明文件。 'node_modules/history/index.js' 隐含一个 'any' 类型

javascript - 页面加载时的 History.js getState()

javascript - 在 Firefox Quantum 中刷新页面后丢失 window.history.state

html - Bootstrap 将内容水平居中并推送/拉取内容

html - 具有 2 种不同背景(和 2 列)的 Bootstrap 全宽

javascript - 根据从表单中选择的值在屏幕上显示数据