0

I want to prompt user to either logout or stay on page as logged-in. I tried using the following code, but not able to find the correct solution:

window.onbeforeunload = function (e) {
          var e = e || window.event;

          // For IE and Firefox
          if (e) {
            e.returnValue = 'Any string';
          }
            alert(doLogout());
          // For Safari
          return 'Any string';
        };

        function doLogout(){
            var r=confirm("Press a button!");
            alert("confirmResponse: " + r);
            return r;
        }

When i tried closing the tab/window, it just asks for "This page is asking you to confirm that you want to leave - data you have entered may not be saved". In my code first confirm dialog should be popped up, which is not happening.

Any solutions ?

Sunil Gulabani
  • 878
  • 1
  • 8
  • 21
  • look at http://stackoverflow.com/questions/7847571/how-can-i-prevent-onbeforeunload-from-firing-when-a-certain-condition-is-met first answer – eventHandler Apr 04 '14 at 17:55

1 Answers1

1

It won't do alert() because of security reasons. This tactic to prevent user from leaving the page was used too often by "bad guys of the internet" so most browser blocked it. Only thing you can do in onunload or onbeforeunload is pass a string that should be displayed to user, before he makes a decision to stay or leave page. You should put you message in place of 'Any string'. That should be sufficient for the user.

Sebastian Piskorski
  • 4,026
  • 3
  • 23
  • 29