Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launching SweetAlert to prevent user from closing window

I am trying to display a message to the user before he closes the window. I am using SweetAlert (http://tristanedwards.me/sweetalert) which is running fine.

The problem is with the JavaScript/jQuery to let me know when the user is trying to close the window/tab and then to display something preventing him from closing the page unless he clicks again.

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        swal("Here's a message!");
        return "You have attempted to leave this page. Are you sure?";
    }
</script>

I have tried this, but it displays the ugly usual message on top of my SweetAlert, any ideas? Without the return part it closes the window anyway, I tried :/

like image 773
leofontes Avatar asked Apr 15 '15 03:04

leofontes


People also ask

How do you use Sweetalert?

SweetAlert is a method to customize alerts in your applications, websites and games. It allows the user to change it with a standard JavaScript button. You can add a new button to it, change the background color of the button, change the button's text, and add additional alerts that depend on the user's click.

How do I get rid of Sweetalert?

First remove closeOnConfirm (it is moved into the button decleration, check this out; https://sweetalert.js.org/docs/#buttons ). Use swall. closeModal(); function for this parameter. Second; for to check result value, use just result.


1 Answers

You can't disable the alert, nor change the style of the alert on onbeforeunload. The main reason is for security problems.

From MDN document, WindowEventHandlers.onbeforeunload, it says,

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog. In Firefox 4 and later the returned string is not displayed to the user. Instead, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved." See bug 588292.

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.

like image 147
Lee Han Kyeol Avatar answered Oct 16 '22 09:10

Lee Han Kyeol