Search code examples
reactjsreact-hooksaddeventlisteneruse-effectonbeforeunload

React: Execute function on website exit, without giving an alert warning


I have a hook that executes the function passed to it when someone leaves the current page, or when they leave the website

const useOnPageLeave = (handler) => {
    useEffect(() => {

        window.onbeforeunload = undefined;
        window.addEventListener('beforeunload', (event) => {             //When they leave the site
            event.preventDefault();                                     // Cancel the event as stated by the standard.
            handler();
        });

        return () => {
            handler();                                                 //When they visit another local link
            document.removeEventListener('beforeunload', handler);
        };
    }, []);
};

When using Firefox or Safari, this alert message appears(only when they leave the site, not when they visit a local link), and I don't want this alert message to show

enter image description here


If I remove the line event.preventDefault(), then the handler function is not executed, and I need the handler event to be executed


Here is an MRE of the problem


Solution

  • const useOnPageLeave = (handler) => {
      useEffect(() => {
        window.onbeforeunload = () => handler();
    
        window.addEventListener('beforeunload', (event) => {
          handler();
        });
    
        return () => {
          handler();
          document.removeEventListener('beforeunload', handler);
        };
      });
    };