How to determine if a user is actually viewing a web page?

Is it possible to determine whether the user is active on the current web page or, say, focused on another tab or window?

It seems that if you switch tabs, any JavaScript set to timeout / interval continues to work. It would be nice to be able to "pause" events when the user is not on the page.

Would it be something like attaching a mouseover event to the body, or would it be too resource intensive?

+3
source share
5 answers

You can post events onfocus/onbluron window.

There is wide support for these events in the window.

: http://jsfiddle.net/xaTt4/

window.onfocus = function() {
    // do something when this window object gets focus.
};

window.onblur = function() {
    // do something when this window object loses focus.
};
+4

- (, , )

+1

, mousemove ( , ). (, ) ​​ x , , script.

body, . , script / (, 1000 ).

0

mousemove, keyup .

I use this throttle / debounce function (which works without jQuery, even if it is a jQuery plugin, if jQuery is present) to run the code in response to them once every ~ 250 ms, so you don’t shoot at the code on every pixel the mouse.

0
source

You can also use the visibilityState of the document:

document.addEventListener("visibilitychange", function() {
  if( document.visibilityState === 'visible' ) {
    // Do your thing
  }
});

This API is widely recognized .

0
source

Source: https://habr.com/ru/post/1791746/


All Articles