Page Vis­i­bil­i­ty API

Publisher: TJ Fogarty

Modified: 2018-03-13

The Page Vis­i­bil­i­ty API lets you detect when a page is vis­i­ble or in focus for a user. The page is deemed no longer vis­i­ble if they switch to anoth­er tab or when the win­dow is minimized.

So what is it good for? The MDN Docs do a great job of explain­ing this API and its poten­tial uses. For exam­ple, you could use it to pause a video or a game, or hold off on any back­ground requests you might be making.

My cas­es are far less noble and excit­ing. Yes, I’m using it to show an emo­ji in the doc­u­ment title. Go ahead, switch to a dif­fer­ent tab. Do come back though. Please. The link to the MDN Docs gives an exam­ple of how to imple­ment the API, along with affor­dances for old­er browsers that sup­port a ven­dor pre­fixed ver­sion. I’m going to out­line a bare­bones script for my implementation.

Here’s the result in case it’s removed or changed.

Page visibility example
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
  }
}

After call­ing PageVisibility.init() you’re good to go. 

[1] We’re stor­ing the orig­i­nal copy of the doc­u­ment title so we can revert back to it once the page is vis­i­ble again.

[2] We do a rudi­men­ta­ry check for mod­ern sup­port for this fea­ture. You can check out the MDN link above for the ven­dor pre­fixed version.

[3] Bind­ing the lex­i­cal scope of this. It means when I call this it’ll refer to the PageVis­i­bil­i­ty object I cre­at­ed rather than document.