到目前为止,这是我的代码,我无法获得-1,为什么我做错了?
我的方法是在组件的历史对象内设置状态,并将其与历史对象的长度进行比较...
async function handleBackForwardButton() {
// If none, then zero
const historyLength = Number(sessionStorage.getItem("historyLength"));
let { state } = await window.history.state;
let position;
if (state === null || state === undefined) {
// New entry on the stack
position = historyLength + 1;
debugger;
// Stamp the entry with its own position in the stack
window.history.replaceState(historyLength, /*no title*/ "");
// (2) Keep track of the last position shown
sessionStorage.setItem("historyLength", String(window.history.length));
debugger;
// (3) Discover the direction of travel by comparing the two
const direction = Math.sign(position - historyLength);
console.log("Forward should be (1) :" + direction);
debugger;
// forward should be (1)
} else if (historyLength > state) {
const direction = Math.sign(state - historyLength);
console.log("Backward should be (-1) :" + direction);
debugger;
//One of backward (-1)
} else if (historyLength === state) {
const direction = Math.sign(state - historyLength);
console.log("Reloading page should be (0) : " + direction);
debugger;
//Reloading page should be (0)
}
}
window.addEventListener("pageshow", handleBackForwardButton);
window.addEventListener("popstate", handleBackForwardButton);