简体   繁体   中英

How can I detect that my a website/PWA has been loaded into the foreground?

I have a Progressive Web App for Ipad written in React, and I'd like to detect when a user reloads the app after switching to another. Is there a browser event or serrvice worker event I can subscribe to for when the app is reloaded?

Along a similar thread, is there a way to tell that a progressive web app has been force closed and reopened?

Thanks

You could make use of a visibilitychange event listener to detect when a web app that was previously in the background is now in the foreground:

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'visible') {
    // Your code here...
  }
});

There's more information about the Page Lifecycle APIs in this post , but you should note that not all of the states available in the API are exposed in Safari. The post lists some caveats to pay attention to when writing code that works across multiple browsers.

You can use the GoogleChromeLabs/page-lifecycle library for a cross-browser method of subscribing to page lifecycle events.

import lifecycle from 'page-lifecycle'

lifecycle.addEventListener('statechange', ({ oldState, newState }) => {
  console.log(`${oldState} -> ${newState}`)
})

In my testing, iOS PWA is limited in which events fire:

  • Switch away : active → passive, passive → hidden
  • Switch to : hidden → passive, passive → active
  • Activate app switcher and back : no change

I did not find any way to detect that the app was force closed and reopened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM