You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测PWA是从启动器打开还是以网页形式访问?

当然可以实现!这在PWA开发中是个挺常见的需求,我来分享几种靠谱的检测方案,覆盖主流浏览器和设备:

检测PWA是否从启动器打开的方法

1. 标准方案:利用display-mode媒体查询

这是W3C定义的标准方式,Chrome、Edge、Firefox等现代浏览器都支持。当用户从启动器打开PWA时,浏览器会将display-mode设置为standalone,而普通标签页打开时是browser模式。你可以通过JS读取这个媒体查询的匹配状态:

const isStandalonePWA = window.matchMedia('(display-mode: standalone)').matches;

2. iOS Safari特殊处理

iOS上的Safari对PWA的支持有自己的特性,它不严格遵循display-mode标准,但提供了navigator.standalone属性来判断:

const isIosStandalone = window.navigator.standalone === true;

这个属性仅在iOS Safari环境下存在,当用户从主屏幕打开PWA时返回true,普通浏览器打开则返回false或undefined。

3. 兼容所有场景的组合检测

把两种方案结合起来,就能覆盖几乎所有主流设备和浏览器了:

function isLaunchedFromHomeScreen() {
  // 检测标准standalone模式
  const standardStandalone = window.matchMedia('(display-mode: standalone)').matches;
  // 检测iOS专属的standalone状态,避免隐私模式下报错
  const iosStandalone = typeof window.navigator.standalone !== 'undefined' && window.navigator.standalone;
  
  // 满足任意一种情况,即视为从启动器打开
  return standardStandalone || iosStandalone;
}

// 使用示例
if (!isLaunchedFromHomeScreen()) {
  // 显示添加到启动器的提示(比如弹出引导弹窗)
  console.log("提示用户:可以把这个PWA添加到你的启动器哦!");
} else {
  // 已经从启动器打开,无需提示
  console.log("PWA已从启动器打开,跳过添加提示");
}

额外提示

  • 部分浏览器还支持fullscreen、minimal-ui等display-mode值,如果你的PWA支持这些模式,可以把它们加入检测条件,比如:
    const isFullscreenOrStandalone = window.matchMedia('(display-mode: standalone), (display-mode: fullscreen)').matches;
    
  • 在iOS的隐私浏览模式下,navigator.standalone可能无法正常返回值,所以上面的组合函数里加了typeof判断来避免报错。

内容的提问来源于stack exchange,提问作者Christian Wattengård

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:58:02