JavaScript, Web Development

JavaScript – Confirm Before Window is Closed

In desktop applications, it is common to have windows that cannot be closed – example: you must save first before closing the window. This is usually done by disabling the close button or setting some application parameters so that it will not be closed no matter what you do.

However, in the web development world, this is not possible. Web browsers won’t allow your website to disable close buttons, nor tell the operating system to deny closing the window. But at least there are other alternatives.

It is common to most websites to prompt a warning message before closing the window. Take a look at the image below – it is using Firefox as an example.

js-confirm-before-close-ff

It lets you choose whether to continue closing the browser or abort closing it. But you still can choose to close it. :'(

Here is the JavaScript code:

/** Confirms when closing the window **/
function checkClose()
{
	$("#s_scan_number").focus();
	return "Please DON'T close the window. Use the form button on the bottom.";
}
window.onbeforeunload = checkClose;

//to remove the confirmation dynamically:
window.onbeforeunload = null;

1 thought on “JavaScript – Confirm Before Window is Closed”

Leave a reply

Your email address will not be published. Required fields are marked *