I have tried capturing the back button action on the browser using pushstate and popstate but problem is pushstate alters the history, thus affecting the normal functioning of back button.
2 Answers
Most people recommend using:
window.onhashchange = function() {
if (window.innerDocClick) {
window.innerDocClick = false;
} else {
if (window.location.hash != '#undefined') {
goBack();
} else {
history.pushState("", document.title, window.location.pathname);
location.reload();
}
}
}
function goBack() {
window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
//blah blah blah
window.location.lasthash.pop();
}

- 1,062
- 7
- 16
-
I dont have any hash in my url. – Neha Gupta Mar 20 '18 at 05:58
-
you can also goBack in else part – Birbal Singh Mar 20 '18 at 06:00
Create an Array that collects the window.location.hash of the user with every change made to window.location.lasthash.
const updateHistory = (curr) => {
window.location.lasthash.push(window.location.hash);
window.location.hash = curr;
}
Unfortunately, there's no native event fired for clicking the browser's back button. However, there is a nice method to faking it using a combination of other native event listeners.
First, set a boolean that gets toggled each time the document is rendered by listening for the onmouseover
event.
const onDocRenderHandler = (bool) => {
window.innerDocClick = bool;
}
document.onmouseover = onDocRenderHandler(true)
After the user clicks the back button, the document again renders so set the boolean flag to toggle again; only this time listening for the onmouseleave
event to fire.
document.onmouseleave = onDocRenderHandler(false)
Finally, listen for theonhashchange
event to fire in between document renders. This simulates a pseudo back button event for us to listen and act on.
const onHashChangeHandler = () => {
if(!window.innerDocClick) {
history.pushState("", document.title, window.location.pathname);
location.reload();
}
}
window.onhashchange = onHashChangeHandler()

- 282
- 3
- 16
-
Check the `updateHistory` function expression I list first. There's where your hash is set. – DaneTheory Mar 20 '18 at 06:01