When users navigate away from a website, it can be beneficial to pause certain activities. Traditionally, JavaScript has lacked a reliable method for detecting window inactivity. Fortunately, advancements in web standards and the Page Visibility API have made this possible.
The Page Visibility API allows developers to determine the visibility state of a website. By subscribing to the "visibilitychange" event, you can detect when the window becomes visible or hidden. Browser support for the API includes:
document.addEventListener("visibilitychange", onchange);
For browsers that do not support the Page Visibility API, you can use a fallback method based on events such as "blur" and "focus." This method is less reliable, but it can be used to achieve similar functionality.
(function() { // Check for standards support var hidden = "hidden"; 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); } // Fallback for IE 9+ else if ("onfocusin" in document) { document.onfocusin = document.onfocusout = onchange; } // Event mapping function onchange(evt) { var hiddenMapping = { focus: "visible", focusin: "visible", pageshow: "visible", blur: "hidden", focusout: "hidden", pagehide: "hidden" }; evt = evt || window.event; if (evt.type in hiddenMapping) { document.body.className = hiddenMapping[evt.type]; } else { document.body.className = document[hidden] ? "hidden" : "visible"; } } // Set initial state if (document[hidden] !== undefined) { onchange({ type: document[hidden] ? "blur" : "focus" }); } })();
The following example shows how to use the Page Visibility API to pause script execution when a browser window is inactive:
document.addEventListener("visibilitychange", function() { if (document.visibilityState === "hidden") { // Pause script execution } else { // Resume script execution } });
By leveraging the Page Visibility API and JavaScript event handling, you can now effectively pause or resume activities based on the visibility state of a browser window.
The above is the detailed content of How Can JavaScript Detect Inactive Browser Windows?. For more information, please follow other related articles on the PHP Chinese website!