Home >Web Front-end >JS Tutorial >How Can I Detect Browser Window Inactivity Using JavaScript?
Determining whether a browser window is not currently active can enhance resource efficiency by preventing unnecessary code execution when the user is not interacting with the site.
Initially, using document blur/focus events was the primary approach. However, the W3C has introduced a more accurate method: the Page Visibility API.
document.addEventListener("visibilitychange", onchange);
This API notifies you when the page becomes visible or hidden to the user.
The Page Visibility API is supported by:
For browsers that don't support the Page Visibility API, the following code provides a fallback:
(function() { var hidden = "hidden"; // Standards: if (hidden in document) document.addEventListener("visibilitychange", onchange); else if ((hidden = "mozHidden") in document) document.addEventListener("mozvisibilitychange", onchange); else if ((hidden = "webkitHidden") in document) document.addEventListener("webkitvisibilitychange", onchange); else if ((hidden = "msHidden") in document) document.addEventListener("msvisibilitychange", onchange); // IE 9 and lower: else if ("onfocusin" in document) document.onfocusin = document.onfocusout = onchange; // All others: else window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange; function onchange (evt) { var v = "visible", h = "hidden", evtMap = { focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h }; evt = evt || window.event; if (evt.type in evtMap) document.body.className = evtMap[evt.type]; else document.body.className = this[hidden] ? "hidden" : "visible"; } // set the initial state (but only if browser supports the Page Visibility API) if( document[hidden] !== undefined ) onchange({type: document[hidden] ? "blur" : "focus"}); })();
This code ensures compatibility with IE 9 and lower, as well as iOS devices that use onpageshow and onpagehide instead of blur/focus events.
The above is the detailed content of How Can I Detect Browser Window Inactivity Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!