2

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>
  • 8
    Trying to mess with the default browser controls without previous interaction is considered bad UX. In addition Rahul's response, I think it'd be good to read [this post](https://stackoverflow.com/questions/57339098/chrome-popstate-not-firing-on-back-button-if-no-user-interaction) and the [MDN page for beforeunload](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event) describing the behavior: "To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all." – Kevin Languasco Apr 16 '20 at 19:35
  • If you want to warn a user that they are going to lose their changes, wouldn't they have to *make a change* in the first place? (Unless you're making changes pro grammatically) – Souleste Apr 17 '20 at 19:40
  • Maybe [this](https://www.helpsystems.com/resources/articles/browser-automation-automate-website-actions-clicks-or-data-extraction) will help? Automate a click event within the web page. – Souleste Apr 17 '20 at 20:34

6 Answers6

6

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 ;)

vrintle
  • 5,501
  • 2
  • 16
  • 46
2

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 = '';
}
Satish Shr
  • 436
  • 4
  • 5
  • Hi Satish, the event you're trying to cancel is actually "not cancelable". You can check it using `.cancelable` property. – vrintle Apr 21 '20 at 03:55
  • https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable. You can check here as it is saying that beforeunload is one of the event that one would like to cancel. – Satish Shr Apr 21 '20 at 05:00
  • Well sorry, I was trying to check your code in codepen. First, I tried your [same code](https://cdpn.io/Rahul_V7/debug/qBOaLMG/VGrWNxezNKpM), and found that the event is not even called. Then, I replaced it with `onpopstate`, which was called, but it was non-cancelable. So, I mistakenly commented that. That's the case. – vrintle Apr 21 '20 at 05:32
  • It will trigger the warning all right BUT on any body unload not on BROWSER BACK button only. E.g. you move from one page to another. That makes it unusable to me. – Boris Gafurov Feb 06 '23 at 17:24
1

I've found a solution on the Google Chrome help page. Try to add history.back()

<script>
    $(function(){
      window.history.pushState({page: 1}, "", "");
      history.back();
      history.forward();
      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>

It seems The problem with Chrome is that it doesn't trigger onpopstate event unless you make browser action (call history.back()). After adding only that makes it works in Chrome but other browsers stop. Adding history.forward() fixes it and starts to work on every browser.

Fateme Mirjalili
  • 762
  • 7
  • 16
0

You need to implement your own logic to handle the back and forward, for the reference you can refer to the following stackoverflow post's answer.

How to Detect Browser Back Button event - Cross Browser

Hope it helps.

Hamza Arshad
  • 856
  • 5
  • 8
  • Did you tried it yourself? As the leading comments to chosen answer is saying that it no longer works, as Chrome updates! – vrintle Apr 21 '20 at 00:59
0

this works for me.

 window.onbeforeunload = function (e) {
                var message = "Are you sure ?";
                var firefox = /Firefox[\/\s](\d+)/.test(navigator.userAgent);
                if (firefox) {
                    //Add custom dialog
                    //Firefox does not accept window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() furthermore
                    var dialog = document.createElement("div");
                    document.body.appendChild(dialog);
                    dialog.id = "dialog";
                    dialog.style.visibility = "hidden";
                    dialog.innerHTML = message;
                    var left = document.body.clientWidth / 2 - dialog.clientWidth / 2;
                    dialog.style.left = left + "px";
                    dialog.style.visibility = "visible";
                    var shadow = document.createElement("div");
                    document.body.appendChild(shadow);
                    shadow.id = "shadow";
                    //tip with setTimeout
                    setTimeout(function () {
                        document.body.removeChild(document.getElementById("dialog"));
                        document.body.removeChild(document.getElementById("shadow"));
                    }, 0);
                }
                return message;
            };
Vijay sadhu
  • 500
  • 4
  • 11
0

From here: How to show the "Are you sure you want to navigate away from this page?" when changes committed?

window.onbeforeunload = function() {
    return true;
};

This will ask the user if he wants to leave the page when he tries to leave it.

I'm pretty sure that's the closes you can go. Because it would be very bad if anyone could just disable the back button for users.

Flafy
  • 176
  • 1
  • 3
  • 15
  • It doesn't not do anything in next.js . May be my code is wrong . i have no idea. I want to prevent back btn to get better UX . Example I have unsaved changes . So I want to Display Default Leave Prompt when Back Btn onClick . – ThanHtutZaw Jun 02 '23 at 09:57