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 :/
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.