Home > Web Front-end > JS Tutorial > How Can I Detect Browser Window Inactivity with JavaScript?

How Can I Detect Browser Window Inactivity with JavaScript?

Barbara Streisand
Release: 2024-12-20 04:31:12
Original
978 people have browsed it

How Can I Detect Browser Window Inactivity with JavaScript?

Detecting Browser Window Inactivity with JavaScript

Many websites perform periodic activities that can be resource-intensive. To optimize performance and user experience, it's beneficial to pause these activities when the user is not actively viewing the page.

The Issue of Window Inactivity Detection

Determining whether a user is actively viewing a browser window or tab is a fundamental challenge in web development. The window.onfocus and window.onblur events provide basic functionality, but they can be unreliable as users can move the focus to other tabs or applications without leaving the window.

The Solution: Page Visibility API

A modern and reliable solution to this problem is the Page Visibility API. Supported by most major browsers, this API provides a way to detect when a page or tab becomes hidden from the user's view.

document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === "hidden") {
    // Pause periodic activities
  } else {
    // Resume periodic activities
  }
});
Copy after login

Unfortunately, this API is not supported by IE 10 and earlier. For these older browsers, a less reliable fallback involving onblur/onfocus and onpageshow/onpagehide events can be used.

var hidden = "hidden";

// Compatibility checks
if (hidden in document) {
  // Supported: Page Visibility API
} else if ((hidden = "mozHidden") in document) {
  // Mozilla-specific
} else if ((hidden = "webkitHidden") in document) {
  // WebKit-based
} else if ((hidden = "msHidden") in document) {
  // Microsoft-specific
} else {
  // Legacy events
}

function onchange(evt) {
  if (evt.type in evtMap) {
    document.body.className = evtMap[evt.type];
  } else {
    document.body.className = this[hidden] ? "hidden" : "visible";
  }
}
Copy after login

By utilizing the Page Visibility API and its fallback, you can effectively detect window inactivity and optimize your code performance accordingly.

The above is the detailed content of How Can I Detect Browser Window Inactivity with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template