DEV Community

TJ Fogarty
TJ Fogarty

Posted on • Originally published at tj.ie

16 5

Page Visibility API

The Page Visibility API lets you detect when a page is visible or in focus for a user. The page is deemed no longer visible if they switch to another tab or when the window is minimized.

So what is it good for? The MDN Docs do a great job of explaining this API and its potential uses. For example, you could use it to pause a video or a game or hold off on any background requests you might be making.

My cases are far less noble and exciting. Yes, I'm using it to show an emoji in the document title. Go ahead, switch to a different tab. Do come back though. Please. The link to the MDN Docs gives an example of how to implement the API, along with affordances for older browsers that support a vendor-prefixed version. I'm going to outline a barebones script for my implementation.

const PageVisibility = {
  asleepEmoji: '💤',
  originalTitle: document.title, // [1]

  init() {
    if (typeof document.hidden === 'undefined') return // [2]

    this.handleVisibilityChange = this.handleVisibilityChange.bind(this) // [3]

    document.addEventListener('visibilitychange', this.handleVisibilityChange, false)
  },

  handleVisibilityChange() {
    let title = this.originalTitle

    if (document.hidden) {
      title = `${this.asleepEmoji} ${title}`
    }

    document.title = title
  }
}
Enter fullscreen mode Exit fullscreen mode

[1] We're storing the original copy of the document title so we can revert back to it once the page is visible again.

[2] We do a rudimentary check for modern support for this feature. You can check out the MDN link above for the vendor prefixed version.

[3] Binding the lexical scope of this. It means when I call this it'll refer to the PageVisibility object I created rather than document.

After calling PageVisibility.init() you're good to go.

Result:

This was originally posted on my blog.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay