0

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 Answers2

0

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();
}
Birbal Singh
  • 1,062
  • 7
  • 16
0

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()
DaneTheory
  • 282
  • 3
  • 16