Javascript 在浏览器中单击“处理后退/前进”按钮 如果用户单击浏览器中的“前进”按钮,我希望console.log(1) -1如果用户单击后退按钮 0如果用户重新加载页面
这是我到目前为止的代码,我无法实现得到-1,为什么我做错了 我的方法是在组件中的历史对象内部设置一个状态,并将其与历史对象的长度进行比较Javascript 在浏览器中单击“处理后退/前进”按钮 如果用户单击浏览器中的“前进”按钮,我希望console.log(1) -1如果用户单击后退按钮 0如果用户重新加载页面,javascript,react-router,browser-history,html5-history,history.js,Javascript,React Router,Browser History,Html5 History,History.js,这是我到目前为止的代码,我无法实现得到-1,为什么我做错了 我的方法是在组件中的历史对象内部设置一个状态,并将其与历史对象的长度进行比较 async function handleBackForwardButton() { // If none, then zero const historyLength = Number(sessionStorage.getItem("historyLength")); let { state } = await
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);
这可能有助于: