0

Hi I tried to use the following javascript to warn users.

 window.onbeforeunload = function() {
       return "Are you sure you wish to leave?";
    };

But I need to make sure that the back button is pressed it seems to call this when you change the url.

Thanks

vaughn
  • 49
  • 1
  • 11
  • this might be helpful https://stackoverflow.com/questions/8980255/how-do-i-retrieve-if-the-popstate-event-comes-from-back-or-forward-actions-with – Corrl Oct 27 '21 at 14:29

1 Answers1

1

Try looking through these answers here.

So, in short, and for people that aren't necessarily using an in-page back button or an array to store the history:

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) {
        //Your own in-page mechanism triggered the hash change
    } else {
        //Browser back button was clicked
    }
}

And there you have it. a simple, three-part way to detect back button usage vs in-page elements with regards to hash navigation.

Your alert would go into the else section of the window.onhashchange handler.

damnedOperator
  • 208
  • 2
  • 13
  • I tired this when I press back on chrome the window.onhashchange is never fired. Any ideas why? – vaughn Feb 23 '23 at 12:50