Starting SweetAlert to prevent the user from closing the window

I am trying to display a message to the user before closing the window. I use SweetAlert ( http://tristanedwards.me/sweetalert ), which works fine.

The problem is that JavaScript / jQuery will tell me when the user tries to close the window / tab, and then display something that prevents the page from closing if it doesn't click again.

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

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

+6
source share
1 answer

You cannot disable the alert or change the alert style to onbeforeunload . The root cause is security issues.

From the MDN document, WindowEventHandlers.onbeforeunload , it says:

When this event returns a non-empty value, the user is prompted to confirm the page is loading. In most browsers, this dialog box displays the return value of the event. In Firefox 4 and later, the returned string is not displayed to the user. Instead, Firefox displays the line "This page asks you to confirm that you want to leave - the data you entered cannot be saved." See Error 588292.

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

Please also note 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 of approximately: config to do the same. In essence, this means that the user always confirms that the document can be uploaded.

+7
source

Source: https://habr.com/ru/post/985153/


All Articles