首页 > 解决方案 > 我可以检测我的 PWA 是作为应用程序启动还是作为网站访问?

问题描述

如果我有 PWA,我可能想要求我的用户将其添加到他们的启动器中,但我不想问它是否实际上是从启动器启动的。

有没有办法从 javascript 中检测到这一点?

标签: javascriptprogressive-web-apps

解决方案


对于 android,您应该只在收到beforeinstallprompt事件后提示用户安装。仅当尚未安装 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/

对于 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


推荐阅读