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

主宰稳场 提交于 2021-01-20 16:51:28

问题


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.

Is there any way to detect this from javascript?


回答1:


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

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




回答2:


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.



来源:https://stackoverflow.com/questions/50543163/can-i-detect-if-my-pwa-is-launched-as-an-app-or-visited-as-a-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!