How to detect iPad and iPad OS version in iOS 13 and Up?

后端 未结 6 2139
攒了一身酷
攒了一身酷 2020-12-06 09:32

I can detect iOS 13 on iPhone but in iPad OS 13 navigator.platform comes as MacIntel. So it is not possible to get iPad identified using below code, but it work

6条回答
  •  萌比男神i
    2020-12-06 10:16

    TL;DR

    const iPad = !!(navigator.userAgent.match(/(iPad)/)
      || (navigator.platform === "MacIntel" && typeof navigator.standalone !== "undefined"))
    

    We can use the navigator.standalone param. It's non-standard and used only on iOS Safari at present:

    Navigator.standalone

    Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.

    When combined with navigator.platform === "MacIntel" iPad's are the only devices that define this property, therefore typeof navigator.standalone !== "undefined" filters out Macs running Safari (touchscreen or not).

    I set up a CodeSandbox and manually tested on Browserstack, seems to work as expected: https://bc89h.csb.app/

    Version Detection (iOS only)

    I haven't tested this too extensively but should give anyone else looking a good place to start:

    const version = navigator.userAgent.match(/Version\/(\d+)\.(\d+)\.?(\d+)?/);
    const major = version && version[1] ? version[1] : "";
    const minor = version && version[2] ? version[2] : "";
    const patch = version && version[3] ? version[3] : "";
    

    The above takes the version and breaks it down into major, minor and patch elements. This seems to work for iOS 12 & 13 which I ran a quick test against. The above SandBox link shows the output.

提交回复
热议问题