Do you ever wonder if background tabs/windows are using battery power, or precious CPU time? Using the Page Visibility API, we can detect when users aren’t viewing/interacting with our website to help them save precious computing resources!

The Page Visibility API was introduced in 2011, and includes several features that were added to the Document object:

  • document.hidden: a read-only attribute that returns true when the tab/window is hidden
  • document.visibilityState: a read-only attribute that returns a string value denoting the state of the tab/window: 'hidden' | 'visible' | 'prerender'
  • visibilitychange an event that’s emitted whenever the tab/window’s visibility changes

The added benefit of using isibilityState over hidden is that you’re able to identify when the browser is in “prerender” phase (eg., when the website is still loading).

Let’s look at some examples that use Page Visibility API!

#api #browser tabs #programming

How to Detect Idle Browser Tabs with the Page Visibility API
1.15 GEEK