A number of other answers have covered how a running Javascript script can tell whether its current window is active or not. However, that's a pretty restrictive set of choices, and makes no distinctions between (for example)
- a minimized window
- an inactive tab
- a floating window partially eclipsed by other programs' floating windows
- a tab that's fullscreened on one monitor while a user does things in another window on the other monitor.
All of these count as inactive, despite the fact that in the latter two cases the webpage remains visible to the user.
While there's evidence that this may be technically impossible given how web browser sandboxes work, I'd still like to be able to detect the differences between the above. For example, pausing an animation for (1) or (2), but keeping it going for (3) or (4). I'm wondering if Javascript (plus frameworks, I guess, or WebAssembly) provides a mechanism to determine this - or, failing that, whether any particular browsers have mechanisms to determine it from within the javascript code of one page.