0

How to call an API on before unload event in react, I have tried fetch with Keepalive true & sendbecon(doesn't support authorization headers in headers)

Also, I want to show dialog box with custom message on unload. the behavior is in consistent.

  // Handle browser tab close or refresh
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      e.preventDefault();
      e.returnValue = '';
     // unlock user API call
      unlock();
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, []);
1
  • "Also, I want to show dialog box with custom message on unload." - developer.mozilla.org/en-US/docs/Web/API/Window/…: "You should note that modern implementations: [...] Only show a generic browser-specified string in the displayed dialog. This cannot be controlled by the webpage code." Commented Jul 23 at 6:37

1 Answer 1

1

You can’t use async/await or Promises in beforeunload handlers.

Option 1: Use sendBeacon + server-side token recognition
If possible, send a token or userId as part of the payload (not header), e.g.:

navigator.sendBeacon('/api/unlock', JSON.stringify({ userId, token }));

Option 2: Use fetch with keepalive: true (limited support):

fetch('/api/unlock', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer yourTokenHere'
  },
  body: JSON.stringify({ userId }),
  keepalive: true
});enter image description here
Sign up to request clarification or add additional context in comments.

1 Comment

Our current logic is with Keepalive is true, 80% of the time it works, but still not happening all the time. And we can't update the Api payload (not belongs to our team)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.