1

I want to intercept the browser back button and call an Ajax function to load a page because my site is entirely Ajax-driven. I’m using both Chrome 75 and Firefox 67.

There are a lot of posts and blog articles about intercepting the browser back button. The best post I found is How to Detect Browser Back Button event - Cross Browser. I implemented his solution this way:

<script>
document.onmouseover = function() {
    //User's mouse is inside the page.
    window.innerDocClick = true;
}

document.onmouseleave = function() {
    //User's mouse has left the page.
    window.innerDocClick = false;
}

window.onhashchange = function() {
    if (window.innerDocClick) {
      console.log("inner click")
        //Your own in-page mechanism triggered the hash change
    } else {
      console.log("outer click")
      ShowPage(3);
        //Browser back button was clicked
    }
}
</script>

The problem is that it doesn’t stop the back button – the browser returns to the previous page before my site is loaded. I want to call the Ajax function ShowPage and interecept the back button, but that’s not happening.

So I replaced it with this:

<script>
function HandleBackFunctionality() {
  console.log("HandleBackFunctionality");
  console.log("Okay, I'm here");
  window.onbeforeunload = function() { return "Your work will be lost."; };
  ShowPage(3);
  return 0;

    if(window.event) {
        if(window.event.clientX < 40 && window.event.clientY < 0)
            console.log("Browser back button is clicked...");
        else
            console.log("Browser refresh button is clicked...");
    } else {
        if(event.currentTarget.performance.navigation.type == 1)
             console.log("Browser refresh button is clicked...");

        if(event.currentTarget.performance.navigation.type == 2)
             console.log("Browser back button is clicked...");
    }
}
</script>

But that doesn’t work at all. I can’t even see if any console.log messages appear because I’m immediately taken to the site last visited before mine.

At this point, all I want to do is stop the back button so I can see the console.log messages. Preferably it will stop the default back button functionality and call my Ajax function.

I didn’t post the code for the function ShowPage because it’s used widely throughout the site so that’s not the problem.

Thanks for any help on intercepting the back button and calling my Ajax function.

RTC222
  • 2,025
  • 1
  • 20
  • 53

0 Answers0