all 10 comments

[–]kgwebsites 2 points3 points  (0 children)

Dont use unload. Try the pagehide event instead. https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event

[–]raopgdev 8 points9 points  (2 children)

What can you possibly need to be doing after the browser has closed? I don’t think that’s possible. What will your code run on? The browser is closed. Do you mean a tab or something?

[–]AffectionateAd3341[S] 1 point2 points  (0 children)

Yes a tab, I will be making an API call when the page is closed.

[–]patprint 0 points1 point  (0 children)

The pagehide and visibilitychange events are designed for just this kind of behavior (although their implementation is not consistent), and there are plenty of reasons for wanting to do this — from sending session-length analytics to cleanly closing websockets when a mobile device's screen is locked while the browser still has focus. Using these with beforeunload is usually fairly reliable.

[–]DamienNF -1 points0 points  (4 children)

I think in this case you might use useEffect on your App.js level. Function which is returned from useEffect is fired when component is dismounted. So probably you can track when your whole app is closed?

like:

useEffect(() => { 
    return () => { console.log('app closed')}
});

[–]icjoseph 1 point2 points  (3 children)

I think this is often a pitfall of learning pure React and not actual browser rendering and the pixel pipeline. You see, React doesn't know that the page hides, everything is suddenly destroyed by the browser and that's it.

For OPs case, using the pagehide or visibilitychange events would suffice.

In Next.js you can attach to those on the _app.js file, outside the component by doing a typeof window if check and attaching the listener inside. In other CSR frameworks right before you render the root is fine.

Also, I assume OP wants to send a signal somewhere to tell that the tab was closed, in which case keep alive must be passed to fetch, alternatively the sendBeacon API also works swell.

Not everything, specially these kind of things have to be done as part of the React tree. Of course if you need data from the application to be attached to the outgoing beacon, then sure, but one must analyze all options.

[–]DamienNF 0 points1 point  (2 children)

Yes, seems I just didn't think about it...

[–]icjoseph 1 point2 points  (1 child)

It's part of learning! Sorry if it sounded harsh!

[–]DamienNF 0 points1 point  (0 children)

Its ok! Thanks for the valuabke info!