Is the user here? Visibility and idleness
Know when the tab is hidden and when the user goes idle.
Apache-2.0Runs on this page
Package: @awacloud/fw
Log tab visibility changes and detect when the user goes idle, with the native idle detector on request or an activity fallback.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
Pause media or polling when the tab is hidden, lock a session after inactivity. The visibility path runs everywhere; the native idle detector needs Chrome or Edge on a secure origin, with a permission asked from a user gesture; elsewhere the page falls back to tracking activity.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Set the idle threshold you need (
watchIdle(60_000)here).
What it shows
visibility.onChange(fn, { immediate: true })giving the state now and on everyvisibilitychange.idle.isSupported()+requestPermission()+create({ threshold })for the native detector, asked only on a click, elseidle.fallback({ threshold, events })with the sameonChangeshape.- One log for both, so you can see what fires when.
- To keep the screen on while the user reads, see
fw/dom-wake-lock.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { visibility } from '@awacloud/fw/dom/lifecycle/visibility.js';
import { idle } from '@awacloud/fw/dom/lifecycle/idle.js';
fw.runtime.registerAllDeep([visibility, idle]);
const VISIBILITY = fw.runtime.resolve('visibility');
const IDLE = fw.runtime.resolve('idle');
/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };
/** @param {string} line */
export function log(line) {
const list = /** @type {HTMLElement} */ (document.getElementById('log'));
list.appendChild(document.createElement('li')).textContent = line;
}
// Visibility: the state now, then every change (pause media, stop polling...).
VISIBILITY.onChange((state) => { show('visibility', state); log(`tab ${state}`); }, { immediate: true });
/**
* Idle detection: the native IdleDetector needs a permission, asked from a
* user gesture; the activity fallback watches input events and a timer.
* @param {number} threshold ms without activity before the user counts as idle
* @param {boolean} [native] try the native detector (call from a click)
* @returns {Promise<{ stop: () => void, mode: string }>}
*/
export async function watchIdle(threshold, native = false) {
const onChange = ({ userState }) => { show('user', userState); log(`user ${userState}`); };
if (native && IDLE.isSupported() && (await IDLE.requestPermission().catch(() => 'denied')) === 'granted') {
const detector = await IDLE.create({ threshold });
detector.onChange(onChange);
await detector.start();
return { stop: () => detector.stop(), mode: 'native IdleDetector' };
}
const fallback = IDLE.fallback({ threshold, events: ['mousemove', 'keydown', 'pointerdown', 'touchstart'] });
fallback.onChange(onChange);
fallback.start();
return { stop: () => fallback.stop(), mode: 'activity fallback' };
}
export let idleWatch = await watchIdle(60_000);
show('user', 'active');
show('idle-mode', idleWatch.mode);
const nativeIdle = /** @type {HTMLButtonElement} */ (document.getElementById('idle-native'));
nativeIdle.hidden = !IDLE.isSupported();
nativeIdle.addEventListener('click', async () => {
const next = await watchIdle(60_000, true);
if (next.mode === idleWatch.mode) { next.stop(); log('native idle detection not granted'); return; }
idleWatch.stop();
idleWatch = next;
show('idle-mode', next.mode);
nativeIdle.disabled = true;
});index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · Is the user here? Visibility and idleness</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Is the user here? Visibility and idleness</h1>
<dl>
<dt>Tab</dt><dd><output id="visibility"></output></dd>
<dt>User</dt>
<dd><output id="user"></output> (<span id="idle-mode"></span>)
<button id="idle-native" type="button">Use the native idle detector</button></dd>
</dl>
<ol id="log" aria-live="polite" aria-label="Lifecycle log"></ol>
</main>
</body>
</html>