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

Harsha Rama picture Harsha Rama · May 15, 2014 · Viewed 20.2k times · Source

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>

Answer

Jonast92 picture Jonast92 · May 15, 2014

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.