- I want to console.log(1) if the user clicks on the forward button inside browser,
- -1 if the user clicks on back button
- 0 if user reloads the page,
This is my code so far, I can not achieve to get -1, why am I doing wrong??
My approach is setting a state inside history object in the component and compare it vs the lenght of the history object...
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);