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?

- 594
- 1
- 8
- 26
2 Answers
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.

- 594
- 1
- 8
- 26
-
7It has been almost two years since I wrote this and today I have come back to learn from Mr. Me-in-the-past. – HolyResistance Aug 28 '21 at 19:24
-
yes, Mr. me is good and always helps – Mar 18 '22 at 16:54
According to MDN window.onBlur
has better browser compatibility.
https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onblur
(Safari - Partial support)
I'm assuming it is easier to use the window
event handler over to document

- 11
- 3