0

I have the following beforeunload function which I have stolen from sonewhere else....

$().ready(function() {
    $("#posManagerLoginForm").trigger("submit");

    $(window).bind("beforeunload", function(){      
        window.setTimeout(function () {
            window.location = "home.htm";
        }, 0);
        window.onbeforeunload = null; // necessary to prevent infinite loop that kills your browser
        return "Press 'Stay On Page' to go to Reporting Manager home";
    });
});

Regardless of what option I select I get navigated to home.htm. Is there a way that I can make the dialog box an ok button instead of the default "Leave Page" or "Stay on page" options?

Or perhaps someone else could make a suggestion on hot to better handle?

thanks

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Richie
  • 4,989
  • 24
  • 90
  • 177
  • possible duplicate of [How can I override the OnBeforeUnload dialog and replace it with my own?](http://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own) – Nerdroid Apr 13 '15 at 06:22

2 Answers2

2

You cannot override the styling of the onbeforeunload dialog. Believe me, I tried this before in my earlier projects.

Reference: http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx

It is built into the browser object, and you have no control over it.

You can however set your own dialog to show when the onbeforeunload event triggers, but it will not disable that the regular one will show. Quite annoying, yes.

urbz
  • 2,663
  • 1
  • 19
  • 29
1

The reason you're still getting redirected is because you're actually doing nothing to prevent it.

If you want to open an alert box before the form gets submitted, make sure the default behaviour is prevented (which is to submit the form), then redirect after OK has been clicked like this:

$().ready(function() {
    $("#posManagerLoginForm").submit(function( event ) {
        event.preventDefault();
        alert("Press 'OK' to go to Reporting Manager home");
        window.location = "home.htm";
    });
});

Though not sure what the use of this would be. If you wanted to stay on the form if a different button is pressed (say 'Cancel' for example), then you'd rather want to use a 'confirm' like this:

$().ready(function() {
    $("#posManagerLoginForm").submit(function( event ) {
        event.preventDefault();
        if confirm(("Press 'OK' to go to Reporting Manager home"))
            window.location = "home.htm";
    });
});

You could replace the alert or confirm with a custom dialog box too, depending on what library you're using. Just make sure you put window.location = "home.htm" inside the dialog's function, otherwise it will execute immediately.

As an example, you may want to have a look into jQuery UI's dialog here: https://jqueryui.com/dialog/

benomatis
  • 5,536
  • 7
  • 36
  • 59