DEV Community

loading...

Detect if a PWA is Visible with the Page Visibility API

wes566 profile image Wes Originally published at goulet.dev on ・1 min read

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

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.

Discussion (0)

Forem Open with the Forem app