Source:  Twitter logo

I have a use case where i want to render a confirmation box when user ties close a browser tab in my react application.

I have a queue which contains the requests to be made to the backend server. I want to render confirmation dialog with some custom message if queue is not empty and user closes browser tab.

Are there any recommended libraries or workflow hwich I should follow to achieve this??

You can use window.onbeforeunload function, to show a popup before closing the browser window.

Eg: Inside the componentDidMount of your component, write the following code:

window.onbeforeunload = function(e) {
  if( //queue not empty ) {
    return;
  }
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
};

This is not in anyway related to React, but just a function provided by the window object. Also check browser compatibility

4 users liked answer #0dislike answer #04
Dane profile pic
Dane
import { useEffect, useState } from 'react';


/**
 * Confirm browser exit.
 *
 * @param defaultEnabled Start as enabled?
 * @param message Custom message (old browsers only).
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
 */
export const useConfirmBrowserExit = (
  defaultEnabled = true,
  message = 'Confirm leave page'
) => {
  const [msg, setMsg] = useState<string>(message);
  const [enabled, setEnabled] = useState<boolean>(defaultEnabled);

  useEffect(() => {
    function listener(e: BeforeUnloadEvent) {
      if (enabled) {
        e.preventDefault();
        e.returnValue = msg;
        return msg;
      }
    }

    window.addEventListener('beforeunload', listener);

    return () => {
      window.removeEventListener('beforeunload', listener);
    };
  }, [msg, enabled]);

  return {
    enable(): void {
      setEnabled(true);
    },
    disable(): void {
      setEnabled(false);
    },
    setMessage(newMessage: string): void {
      setMsg(newMessage);
    },
    getMessage(): string {
      return msg;
    },
    setEnabled(status: boolean): void {
      setEnabled(status);
    },
    getEnabled(): boolean {
      return enabled;
    },
  };
};

Note

From https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

The support for custom messages have been removed.

2 users liked answer #1dislike answer #12
Eduardo Cuomo profile pic
Eduardo Cuomo

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).