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>
添加回答
舉報