DEV Community

Wes
Wes

Posted on • Originally published at goulet.dev on

2 2

Detect if a PWA is Visible with the Page Visibility API

Need to figure out when your PWA comes to the foreground? The modern web has you covered with the Page Visibility API.

document.addEventListener("visibilitychange", () => {
  const state = document.visibilityState;
  if (state === "hidden") {
    // your PWA is now in the background
  }

  if (state === "visible") {
    // your PWA is now in the foreground
    refreshData();
  }
});
Enter fullscreen mode Exit fullscreen mode

Note: this API isn't specific to PWAs, it works for non-PWA websites/webapps as well.

Most documentation talks about how this event fires when switching tabs, but this also fires when a PWA is foregrounded/backgrounded.

Try it out yourself by going to https://visibility-api.netlify.app and adding it to your home screen.

Hopefully you found this post helpful, if you have any questions you can find me on Twitter.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay