Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert on Browser Back button click or page refresh

I have seen the same function is multiple sites including SO. I am also trying to achieve this. Here is the code so far.

 <script>
            var myEvent = window.attachEvent || window.addEventListener;
            var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; 

            myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
                var confirmationMessage = ' ';  
                (e || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            });
        </script>

The problem is above code is working fine in chrome and IE but when I tried to test in on Firefox it is not working. I checked firebug but there is no error. I updated the firefox and version are 47.0.1.

But issue not fixed.

Any advice would be helpful.

Guys if you have code better than this then it would be also helpful.

like image 989
Roxx Avatar asked Oct 25 '25 12:10

Roxx


1 Answers

Use below code, I tested it in firefox and is working fine :

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});
like image 156
shivgre Avatar answered Oct 28 '25 01:10

shivgre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!