Detect browser or tab close event using JavaScript

Today we’ll show you how to detect browser or tab close event using JavaScript and perform some operations like database update or data manipulation. Sometimes you can use it to warn the user before leaving the page.

In this JavaScript article, we will show you how to perform operation before closing the browser/tab. Also we will give you another example where we can show alert to the user before reload or close the tab/browser.

In both cases, we will use the beforeunload event to detect the close event.

Way to detect browser or tab close event

  1. Perform database operation before close the browser (without alert)
  2. Show alert before close/reload the tab or browser

1. Perform database operation before close the browser (without alert)

Here, we will use the addEventListener() method to handle the beforeunload event to detect browser close. Use the following code to perform the DB operation or data manipulation.

In the above code, we have added the delay for database operation otherwise it will not happen.

2. Show alert before close/reload the tab or browser

In the second way, we will warn the user before reloading or leaving the page.

In the above example, we have added the input field for user interaction because most browsers require interaction with a page/site, otherwise a warning box will not be shown.

Output: On page reload

Reload page - Detect browser or tab close event using JavaScript - Clue Mediator
Reload page – Detect browser or tab close event using JavaScript – Clue Mediator

Output: On tab/browser close

Close page - Detect browser or tab close event using JavaScript - Clue Mediator
Close page – Detect browser or tab close event using JavaScript – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

You may also like...

Leave a Reply

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