2 回答
TA贡献1797条经验 获得超6个赞
我在 MDN 上找到了一个注释。它说:
注意:调用history.pushState()或history.replaceState()不会触发popstate事件。popstate 事件仅通过执行浏览器操作来触发,例如在同一文档的两个历史记录条目之间导航时单击后退按钮(或在 JavaScript 中调用history.back())。
我建议您将事件处理程序注册到WindowEventHandlers 的 onpopstate 属性addEventListener()
,而不是注册到WindowEventHandlers的onpopstate属性。
例子:
<html>
<head>
<meta charset="utf-8" />
<script>
// ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event
window.addEventListener('popstate', function(e) {
alert('onpopstate');
}
setTimeout(function () {
history.pushState(1, 'Hello John', '/hello/john');
}, 2000);
setTimeout(function () {
history.pushState(2, 'Hello Emily', '/hello/emily');
}, 3000);
</script>
</head>
<body></body>
</html>
TA贡献1864条经验 获得超2个赞
使用 anObject
表示state
。
状态对象是一个 JavaScript 对象,与 PushState() 创建的新历史记录条目相关联。每当用户导航到新状态时,都会触发 popstate 事件,并且该事件的 state 属性包含历史记录条目的状态对象的副本。
const log = Logger();
// create 3 'history pages'
history.pushState({page: 1, greet: "Hello John"}, '', "#John");
history.pushState({page: 2, greet: "Hello Emily"}, '', "#Emily");
history.pushState({page: 3, greet: "Hello James"}, '', "#James");
log(`current history state: ${JSON.stringify(history.state)}`);
// on popstate log the history state if applicable
window.addEventListener("popstate", () =>
history && history.state && log(`${history.state.greet || ""} @page ${
history.state.page} (location: ${location.hash})`)
);
// listener for the buttons
document.addEventListener("click", evt => {
if (evt.target.nodeName === "BUTTON") {
return evt.target.id === "back" ? history.back() : history.forward();
}
});
// helper function for logging in the document
function Logger() {
let logEl;
if (typeof window === "object") {
logEl = document.querySelector("#log") || (() => {
document.body.append(
Object.assign(document.createElement('pre'),
{id: "log"}));
return document.querySelector("#log");
})();
return (...logLines) =>
logLines.forEach(s => logEl.textContent += `${s}\n`);
} else {
return (...logLines) =>
logLines.forEach(ll => console.log(`* `, ll));
}
}
<button id="back"><< 1 back</button>
<button id="forward">1 forward >></button>
添加回答
举报