Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirm reload page with a custom dialog box inside onbeforeunload function. Code to be executed in the function onbeforeunload before box popsup [duplicate]

I want to show a confirm box when a user tries to reload a page. I have tried it in my project and it did not work. I have created a sample code of what i have tried and even it is not working. Can anybody tell where i have gone wrong. I am not even getting the confirm box. I am using Chrome 33+. I need to execute some code in the window.onbeforeunload before the box pops up.

<!DOCTYPE>
<html>
<body>
    <script type="text/javascript">
        window.onbeforeunload = function()
        {
          var r = confirm("Are you sure you want to reload the page.");
          if(r)
          {
            window.location.reload();
          }
          else
          {

          }
        };

    </script>
</body>
</html>
like image 250
Harsha Rama Avatar asked May 15 '14 13:05

Harsha Rama


1 Answers

This will work:

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

Recent versions of Chrome (and probably a few others) don't support anything but returning a simple message when using onbeforeunload. Other code in the function seems to be ignored, at least in Chrome.

Will do the trick for you. You can return something different (make it be custom) than the empty string but that will cause duplicate questions (your message + the one provided by the browser) but there's nothing stopping you from doing it.

Tested in IE9 and newest version of Chrome. It will launch an alert box, asking whether the user wants to reload or not.

like image 105
Jonast92 Avatar answered Oct 18 '22 18:10

Jonast92