简体   繁体   English

我能否检测我的 PWA 是作为应用程序启动还是作为网站访问?

[英]Can I detect if my PWA is launched as an app or visited as a website?

If I have a PWA I might want to ask my user to add it to their launcher, but I don't want to ask this if it's actually launched from the launcher.如果我有一个 PWA,我可能想让我的用户将它添加到他们的启动器中,但我不想问它是否实际上是从启动器启动的。

Is there any way to detect this from javascript?有没有办法从javascript中检测到这一点?

For android, you should only prompt users to install after receiving a beforeinstallprompt event.对于 android,您应该只在收到beforeinstallprompt事件后提示用户安装。 This event will only be fired if the PWA has not already been installed.只有在尚未安装 PWA 时才会触发此事件。

window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  deferredPrompt = e;
  // Update UI notify the user they can add to home screen
  btnAdd.style.display = 'block';
});

https://developers.google.com/web/fundamentals/app-install-banners/ https://developers.google.com/web/fundamentals/app-install-banners/

For IOS, you can check window.navigator.standalone , which should be true if the app has already been installed.对于 IOS,您可以检查window.navigator.standalone ,如果应用程序已经安装,则应该为 true。

// Detects if device is on iOS 
const isIos = () => {
  const userAgent = window.navigator.userAgent.toLowerCase();
  return /iphone|ipad|ipod/.test( userAgent );
}
// Detects if device is in standalone mode
const isInStandaloneMode = () => ('standalone' in window.navigator) && (window.navigator.standalone);

// Checks if should display install popup notification:
if (isIos() && !isInStandaloneMode()) {
  // offer app installation here
}

https://www.netguru.co/codestories/few-tips-that-will-make-your-pwa-on-ios-feel-like-native https://www.netguru.co/codestories/few-tips-that-will-make-your-pwa-on-ios-feel-like-native

To put it in another way, you dont have to do any code to achieve this.换句话说,您不必编写任何代码来实现这一点。 Browser triggeres Install to home screen banner/related events, only if its used in a browser and wont happen from launcher.浏览器触发安装到主屏幕横幅/相关事件,仅当它在浏览器中使用并且不会从启动器发生时。

What you expect to do is the default behavior of how web install banners work.您期望做的是 Web 安装横幅如何工作的默认行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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