How can I capture if a user closes the browser before clicking on the submit button?

Question

How can I capture if a user closes the browser before clicking on the Submit button?

Answer

If you want to capture whether a user is trying to close the browser before submitting the form, this can be done, but only usingJavaScript as this is a browser event happening at client-side.

The function is window.onbeforeunload.

Example

<script language=javascript>
window.onbeforeunload = function() {
 if (MySubmitButtonIsClicked == false)
return "Are you sure you want to exit??";
}
</script>

Note: Keep in mind that this message will always appear when your page is unloaded, whether it is a new web page that is loaded within the same window or the whole browser window itself is closed. It is important that your condition makes sure the alert message does not appear if a desired action has occurred.