Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React window unload event doesn't fire

I need to use navigator.sendBeacon() on window unload in order to let my server know the client has closed his window. I have searched everywhere and it just doesn't work for me.

For reference, the solution in this post didn't work either.

I have an App component that wraps my entire project. I am trying to set the unload event on it's componentDidMount() lifecycle method, and it just won't fire.

componentDidMount() {
  window.addEventListener("beforeunload", this.unload);
}

componentWillUnmount() {
  window.addEventListener("beforeunload", this.unload);
}

unload(e) {
  e.preventDefault();
  e.returnValue = 'test';
  navigator.sendBeacon(`http://localhost:8080/window-closed/${this.props.username}`);
  return 'test';
}

I expect the server to get the AJAX call, and the window to prompt the user 'test' before the window is closed. What actually happens is the window just closes as usual.

NOTE: the return 'test' & e.returnValue = '' statements are purely for testing. I'm only interested in the AJAX request.

Any help would be much appreciated.

like image 761
Sagi Rika Avatar asked Jul 24 '26 09:07

Sagi Rika


2 Answers

If you're using a functional component, you can try this:

 useEffect(() => {
    window.addEventListener("beforeunload", handleUnload);
    return () => {
      window.removeEventListener("beforeunload", handleUnload);
    };
  }, []);

  const handleUnload = (e) => {
    const message = "o/";
    (e || window.event).returnValue = message; //Gecko + IE
    return message;
  };


like image 195
Prottay Avatar answered Jul 26 '26 23:07

Prottay


You may be able to use navigator.sendBeacon.

const UnloadBeacon = ({
  url,
  payload = () => {},
  children
}) => {
  const eventHandler = () => navigator.sendBeacon(url, payload())

  useEffect(() => {
    window.addEventListener('unload', eventHandler, true)
    return () => {
      window.removeEventListener('unload', eventHandler, true)
    }
  }, [])

  return children
}

full example here: https://gist.github.com/tmarshall/b5433a2c2acd5dbfc592bbc4dd4c519c

like image 21
Marshall Avatar answered Jul 26 '26 22:07

Marshall