You cannot control when user will refresh the web page and close it, but it’s important sometimes to display confirmation alert before closing the Tab.
The user may be mistaken clicked the close button and lost some important data.
You have seen in Shopping websites when you are in the middle of payment or you are paying the Bill and if you try to refresh the web page then it will show a confirm alert on the screen.
When is it Required ?
- When the form has many fields and the user filled the form but somehow the Browser is being closed. Now, the user needs to again fill that long form.
- While student giving the online test and not completed yet and he/she try to close or refresh the page.
- There are many other situations where you can use it.
onbeforeunload event trigger when tries to close, refresh the tab or closing the Browser.
You can use this to display an alert message on the Browser for this you only need to return your message text.
You can also perform in this way also –
<body onbeforeunload=" return 'Are you really want to perform the action?'">
As I said at the start of this tutorial, you cannot fully control the web page because you are not the owner of the Browser, you can only access limited info.
For example, you can only catch when the tab is closing but you don’t get any information why is closing.
But somehow it’s better to show a confirm box which asks the question to the user and this gives a chance to get back if the action is performed mistaken.