The MDN docs say that the visibilitychange
event
fires with a visibilityState of hidden when a user navigates to a new page, switches tabs, closes the tab, minimizes or closes the browser, or, on mobile, switches from the browser to a different app.
While I recall having experience with this being true, it looks like it isn't anymore (at least not on either Chrome or Firefox). I'm currently on desktop Chrome Version 121.0.6167.160
To reproduce, if I look at the end-of-session analytics example and basically copy-paste the function into the browser console like
document.onvisibilitychange = () => {
console.log(document.visibilityState);
};
then I'll see "hidden" and "visible" logged to the console as I switch between open tabs. However, if I then click a random link that takes me to another page, nothing is logged and so I'm left to assume that the visibilitychange event is not firing in this case (the preserve-log option is checked in the dev console).
And just as an ultra-sanity check, the same behavior happens if I replace the console log with an actual sendbeacon request.
It sounds unlikely that a browser bug was pushed since it's happening in both chrome and firefox, so what am I missing / not understanding here?
beforeunload
event has problems -- it's not reliably fired on mobile and also apparently isn't compatible with the bfcache on firefox according to mdnonclick=e=>{ onclick = null; const win=open("./"); document.onvisibilitychange=()=>win.document.body.textContent=document.visibilityState; }
Basically we open a popup window on click and then write to it in the event.