且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查是否在Android的主屏幕上添加了网络应用

更新时间:2023-11-30 22:03:10

是的,可以.

虽然从技术上讲,在Chrome浏览器选项卡中打开的页面无法直接检查主屏幕快捷方式是否存在,但是该页面的本地数据(localStorage,IndexedDB)在主屏幕实例和浏览器选项卡之间共享,因此可以使用传达主屏幕版本的存在.

While technically a page open in Chrome browser tab can't directly check whether a home screen shortcut exists, the page's local data (localStorage, IndexedDB) is shared between home screen instance and browser tabs, so this can be used to communicate the existence of the home screen version.

  1. 检测应用是否从主屏幕运行
  2. 如果它是从主屏幕运行的,请将此事实保存到localStorage
  3. 利润! (通过从任何标签中的localStorage读取此信息)
  1. Detect if the app is running from home screen
  2. If it's ran from home screen, save this fact to localStorage
  3. Profit! (by reading this from localStorage in any tab)

当应用处于独立视图中时(仅当从主屏幕启动时才可能),CSS媒体查询(display-mode: standalone)将匹配.在Javascript中,您可以使用以下方法阅读它:

When the app is in standalone view (which is possible only when launched from home screen), the CSS media query (display-mode: standalone) will match. In Javascript you can read it using:

matchMedia('(display-mode: standalone)').matches

(顺便说一句:非标准的iOS等效项是navigator.standalone,但是iOS不在主屏幕和Safari之间共享状态,因此您不走运).

(BTW: the non-standard iOS equivalent of this is navigator.standalone, but iOS doesn't share state between home screen and Safari, so you're out of luck there).

但是,我建议您不要使用自定义说明,而应满足Chrome的渐进式网络应用"标准,然后让Chrome为您进行提示.

However, instead of custom instructions I suggest meeting Chrome's criteria for "progressive web app" and let Chrome do the prompting for you.