In ECMAscript (=Javascript) there are two ways to check if the user is away from your page or not. You can either listen for a "visibilitychange
" event on the document
or you can listen for "blur
" and "focus
" events on the window
. Is there a difference between them?
The window. blur() method is the programmatic equivalent of the user shifting focus away from the current window.
The visibilitychange event is fired at the document when the contents of its tab have become visible or have been hidden. The event is not cancelable.
Note: The Page Visibility API is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible.
Yes. The most significant difference between them can be seen on phones. On desktop and tablet devices when you want to change the browser tab there is only ONE step to do so. You just click/tap where you want to go and you are there. It looks like this,
But on a phone normally there are TWO steps. You first start like this,
and when you tap on the TABS icon you see a fly-over menu like this,
This is where the main difference between visibilitychange and blur/focus becomes obvious and can also be important. According to "visibilitychange
" the user is not yet away from your page at this stage. But according to "blur
/focus
" the user is away.
As for other cases, I used both to see which one fires before. The code is,
document.addEventListener("visibilitychange", visChngF);
function visChngF()
{
if (document.hidden) {
console.log("hidden means user is gone");
} else {
console.log("visible means user is back");
}
}
window.addEventListener('blur', blurHappenedF);
function blurHappenedF()
{
console.log("blur means user is away");
}
window.addEventListener('focus', focusHappenedF);
function focusHappenedF()
{
console.log("focus means user is here");
}
Result: It is unpredictable. Sometimes visibilitychange fires before blur/focus and sometimes it is after. It may even fire between a blur event and a focus event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With