我能否检测我的 PWA 是作为应用程序启动还是作为网站访问? [英] Can I detect if my PWA is launched as an app or visited as a website?

查看:72
本文介绍了我能否检测我的 PWA 是作为应用程序启动还是作为网站访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 PWA,我可能想让我的用户将它添加到他们的启动器中,但我不想问它是否真的是从启动器启动的.

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.

有什么办法可以从 javascript 中检测到这一点吗?

Is there any way to detect this from javascript?

推荐答案

对于 android,您应该只在收到 beforeinstallprompt 事件后才提示用户安装.只有在尚未安装 PWA 时才会触发此事件.

For android, you should only prompt users to install after receiving a beforeinstallprompt event. This event will only be fired if the PWA has not already been installed.

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-安装横幅/

IOS 可以勾选window.navigator.standalone,如果应用已经安装,应该是这样.

For IOS, you can check window.navigator.standalone, which should be true if the app has already been installed.

// 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

这篇关于我能否检测我的 PWA 是作为应用程序启动还是作为网站访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆