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

How Can I Detect Browser Window Inactivity Using JavaScript?

DDD
DDDOriginal
2024-12-24 20:18:18747browse

How Can I Detect Browser Window Inactivity Using JavaScript?

Detecting Browser Window Inactivity with 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.

The Page Visibility API

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.

Browser Compatibility

The Page Visibility API is supported by:

  • Chrome 13
  • Internet Explorer 10
  • Firefox 10
  • Opera 12.10

Fallback for Incompatible Browsers

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!

Statement:
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