用JavaScript检测iPadOS 和 iOS的最新方法

新iPad的window.navigator.userAgent,已经没有iPad的字符串标识,Safari打印出来类似:

mozilla/5.0(macintosh; intel mac os x 10_15_7) applewebkit/605.1.15(khtml, like gecko)

呃呃,竟然是macintosh,要和电脑终端逐步融合的节奏。

推荐用设备触摸点数maxTouchPoints来判断,并兼容旧版本:

const isIOS = () => {
  if (/iPad|iPhone|iPod/.test(navigator.platform)) {
    return true;
  } else {
    return navigator.maxTouchPoints &&
      navigator.maxTouchPoints > 2 &&
      /MacIntel/.test(navigator.platform);
  }
}

const isIpadOS = () => {
  return navigator.maxTouchPoints &&
    navigator.maxTouchPoints > 2 &&
    /MacIntel/.test(navigator.platform);
}

参考资料:https://thewebdev.info/2022/02/11/how-to-detect-ipad-pro-as-ipad-with-javascript/