Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Document visibilitychange versus window blur/focus, what is the difference, when to use which?

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?

like image 570
PWA-developer Avatar asked Sep 28 '19 16:09

PWA-developer


People also ask

What is window blur?

The window. blur() method is the programmatic equivalent of the user shifting focus away from the current window.

What is Visibilitychange?

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.

Why do you think Pagevisibility API is useful?

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.


1 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, tablet

But on a phone normally there are TWO steps. You first start like this,

phone

and when you tap on the TABS icon you see a fly-over menu like this,

phone tabs

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.

like image 104
PWA-developer Avatar answered Sep 22 '22 14:09

PWA-developer