[英]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.我有一个用 React 编写的 Ipad 的渐进式 Web 应用程序,我想检测用户在切换到另一个应用程序后何时重新加载应用程序。 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?沿着类似的线索,有没有办法告诉渐进式 web 应用程序已被强制关闭并重新打开?
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:您可以使用
visibilitychange
事件侦听器来检测以前在后台的 web 应用程序现在何时在前台:
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.在这篇文章中有更多关于页面生命周期 API 的信息,但您应该注意,并非 API 中可用的所有状态都在 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.您可以使用GoogleChromeLabs/page-lifecycle库作为订阅页面生命周期事件的跨浏览器方法。
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:在我的测试中,iOS PWA 在触发事件时受到限制:
I did not find any way to detect that the app was force closed and reopened.我没有找到任何方法来检测该应用程序被强制关闭并重新打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.