How to know a Browser Tab Close or Refresh with JavaScript

You cannot control when user will refresh the web page and close it, but it’s important sometimes to display a confirmation alert before closing the Tab.

The user may be mistakenly 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 try to close or refresh the page.
  • There are many other situations where you can use it.

In this post, I discuss How you can detect Browser Tab close and refresh using JavaScript.

How to know a Browser Tab Close or Refresh with JavaScript


Contents

  1. onbeforeunload
  2. Conclusion

1. onbeforeunload

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.

Example 

<script type="text/javascript">
window.onbeforeunload = function () {
   return 'Are you really want to perform the action?';
}
</script>

You can also perform in this way also –

<body onbeforeunload=" return 'Are you really want to perform the action?'">

2. Conclusion

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 that asks the question to the user and this gives a chance to get back if the action is performed mistakenly.

If you found this tutorial helpful then don't forget to share.