最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I detect that my a websitePWA has been loaded into the foreground? - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Oct 7, 2019 at 15:23 Alexander TroupAlexander Troup 1871 silver badge13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论