I am working on React project with hooks. I add below to make a leave site message when close chrome tab. The effect is like the picture below.
useEffect(() => {
window.addEventListener('beforeunload', (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = '';
});
}, []);
It does work on laptop'browse, but does not work on both mobile and tablet computer'browse. It cannot show the alert like chrome did on laptop. Anyone had this problem before?
The event beforeunload
is not 100% reliable, especially on mobile, as you have seen. The unload event does not fire in some common cases such as closing an app (browser) from the app switcher or closing a browser tab on mobile.
To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.
I would recommend to check this documentation. Here you will find that it is recommended to rely the visibilitychange
event to determine when a session ends.