How To Handle The Browser Tab Close Event In React

Handle the Browser Tab close event in React

Knowing how to handle the browser tab close event in React will make you do some cool things, like checking if the user inserts some data and wants to out the page. So how to do it? Let’s go into detail now.

Handle the browser tab close event in React

Using onbeforeunload event

The onbeforeunload event will be triggered whenever the window or the tab is unloaded. So that I can return some value to turning the message on, noticing the user is reloading the page.

Example:

import { useEffect } from "react";

const App = () => {
  // With the useEffect hook, the code will be executed on everytime component mount
  useEffect(() => {
    // Create a function to handle close tab event
    const handleCloseEvent = (event) => {
      event.preventDefault();
      return (event.returnValue = "");
    };

    // Add an event to the window object
    window.onbeforeunload = handleCloseEvent;
  }, []);

  return (
    <div>
      <h2>hello world</h2>
    </div>
  );
};

export default App;

Output:

As you see here, by adding an event on the window object, the handleCloseEvent function will be executed before the browser is loaded. The user can confirm and navigate to the new page.

I use the useEffect to add the event to the window and pass an empty array in the dependencies array so it runs when the component mounts.

In history, we used to be config reload messages. But developer becomes abuse it, now we can only see the default message like this:

Using beforunload event

With the beforunload event, we will execute code like onbeforeunload, but we will need to combine it with addeventlistener to add the event to the window object.

Example:

import { useEffect } from "react";

const App = () => {
  // With the useEffect hook, the code will be executed on every time component mount
  useEffect(() => {
    const handleCloseEvent = (event) => {
      event.preventDefault();
      return (event.returnValue = "");
    };

    window.addEventListener("beforeunload", handleCloseEvent);

    // Remove event
    return () => {
      window.removeEventListener("beforeunload", handleCloseEvent);
    };
  }, []);

  return (
    <div>
      <h2>hello world</h2>
    </div>
  );
};

export default App;

The function we return from the useEffect hook will be called when the component unmounts from the page. So we can apply it to clean events from the window object. The clean step is also very important in preventing you from leaking any information about your website.

Summary

In this article, I showed you how to handle the browser tab close event in React. I recommend you add the event beforeunload to the window object so that you can show a default message before the user close tab.

Maybe you are interested:

Leave a Reply

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