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 :/
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With