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

How Can I Detect Browser Tab Activity Using JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 07:35:11314browse

How Can I Detect Browser Tab Activity Using JavaScript?

Browser/Tab Activity Detection [Duplicate]

In the realm of JavaScript, it's often desirable to only execute code when the current page is actively visible to the user. This is a common scenario for CPU-intensive operations that are unnecessary to perform while the browser or tab is in the background.

To address this, the Page Visibility API provides a reliable solution. The document.hidden property indicates whether the page is hidden from view (such as when the browser is minimized or another tab is active):

if (!document.hidden) {
    // Do what you need
}

In addition, here are some notable resources for further understanding:

  • David Walsh's article on page visibility: http://davidwalsh.name/page-visibility
  • Google Chrome whitepaper on page visibility: https://developers.google.com/chrome/whitepapers/pagevisibility
  • Example of pausing video playback when the tab is inactive: https://web.archive.org/web/20170609212707/http://www.samdutton.com/pageVisibility/

The above is the detailed content of How Can I Detect Browser Tab Activity 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