Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to warn the user when click on the browser back button

I would like to warn the user when they click on the browser "back button" then redirect them upon confirmation. Below is my JS code but works only in firefox, I would like to make it work in chrome and other browsers as well.

Note: In order for the event to be fired in chrome, I need first to click on the page body then click on browser "back" button(this is not good).

Please assist.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page2</title>
</head>
<body>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>
  <script>
    $(function(){
      window.history.pushState({page: 1}, "", "");
      window.onpopstate = function(event) {
        if(event){
          var confirm = window.confirm("Please, note that you may lose your move details by returning to the previous page.");
        }
      }
    });
  </script>
</body>
</html>
like image 788
christian nyembo Avatar asked Nov 07 '25 18:11

christian nyembo


2 Answers

I'd found a useful link, which explains such a behavior of Chrome and other browsers.

"Chrome plans to save you from sites that mess with your back button"

Some of the nuisance sites mentioned in above post, uses this behavior, in their favor. So, it seems that browsers like Chrome are intentionally preventing these kind of sneaky hacks with the "back button" (obviously due to security reasons and smooth user-experience). Also, I doubt if anyone finds a pretty hack, then Chrome developers will again evolve their security checks, as said in the post.

Anyways, we still have Firefox with us. Good luck ;)

like image 156
vrintle Avatar answered Nov 09 '25 06:11

vrintle


Just like you said you first need to click on the body to activate confirm dialog and whenever user tries to leave the page will show the confirmation dialog.

window.onbeforeunload = (event) => {
event.preventDefault();
event.returnValue = '';
}
like image 43
Satish Shr Avatar answered Nov 09 '25 08:11

Satish Shr