How to Detect Browser Close Event in Javascript

In web development, it is important to detect certain events such as a browser close event in order to handle any unfinished tasks or to clean up any resources that might still be in use. In this tutorial, we will learn how to detect the browser close event in JavaScript.

To detect the browser close event, we need to use the beforeunload event in JavaScript. This event is triggered just before the browser window is about to close. We can use this event to handle any unfinished tasks or to prompt the user if they want to leave the page.

HTML & CSS:

  • We have a button element with an ID of save-button and a paragraph element with an ID of message.
  • The message element is initially hidden using CSS by setting the display property to none.
  • We have also included our JavaScript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html>
  <head>
    <title>Browser Close Event</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div>
      <button id="save-button">Save Changes</button>
      <p id="message">Changes saved successfully!</p>
    </div>
    <script src="script.js"></script>
  </body>
</html>
#message {
  display: none;
}

Javascript:

  • We have selected the save-button element using document.querySelector() method and stored it in the saveBtn variable.
  • We have added a click event listener to the saveBtn element.
  • In the event handler function, we are showing the message element by changing its display property to block.
  • We have also added a beforeunload event listener to the window object.
  • In the beforeunload event handler function, we are setting the value of the returnValue property to a string. This string will be displayed to the user in a prompt when they try to leave the page.
const saveBtn = document.querySelector('#save-button');
const message = document.querySelector('#message');

saveBtn.addEventListener('click', () => {
  message.style.display = 'block';
});

window.addEventListener('beforeunload', (event) => {
  event.preventDefault();
  event.returnValue = 'Are you sure you want to leave this page? Your changes may not be saved.';
});

In this code example, when the user clicks on the Save Changes button, the message element will be displayed. If the user tries to leave the page by closing the browser window or by clicking on a link, a prompt will be displayed with the message Are you sure you want to leave this page? Your changes may not be saved and the user can choose to stay on the page or leave the page.

I hope this tutorial has helped you to understand how to detect the browser close event in JavaScript.