What I know it's possible to detect if page is in foreground or in background - or more precisely: if has focus or has not focus.
var focus = true;
window.onblur = function() { focus = false; action(); }
window.onfocus = function() { focus = true; action(); }
document.onblur = window.onblur;
document.focus = window.focus;
function action(){
if(focus) {
document.body.style.background = "green";
} else {
document.body.style.background = "lightgray";
}
}
try click inside and then outside
The above code snippet uses event listeners onblur
and onfocus
for events focus
and blur
.
Better can be to use Visibility API:
- it works when switching tabs (page can detect that user has opened another tab)
Note: While onblur and onfocus will tell you if the user switches windows, it doesn't necessarily mean it's hidden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab.
see Detect if browser tab is active or user has switched away
http://jsbin.com/lowocepazo/edit?js,output
For scrolling there is an Intersection Observer
provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport
//EDIT:
Nowdays is not possible to detect such cases like for example in 1st video you posted (in 2:09) when another window is obscured some element:

If I'm wrong, please correct me.
related: