Tell iPadOS from macOS on the web

后端 未结 4 1481
南笙
南笙 2020-12-08 15:24

The user agent of Safari on iPadOS beta is at this point exactly the same as Safari on macOS. Is there any other way to tell an iPad from a Mac?

iPad running         


        
相关标签:
4条回答
  • 2020-12-08 15:54

    I'm using this test client side:

       if (navigator.userAgent.match(/Mac/) && navigator.maxTouchPoints && navigator.maxTouchPoints > 2) {
         ...must be iPad OS...
    

    Since there's no official touch screen for Mac, it seems pretty safe. The actual value of maxTouchPoints on the iPad is 5, BTW.

    0 讨论(0)
  • 2020-12-08 15:55

    I'm using this works fine:

    const ua = window.navigator.userAgent.toLowerCase();
    const isiPad = ua.indexOf('ipad') > -1 || ua.indexOf('macintosh') > -1 && 'ontouchend' in document;
    
    0 讨论(0)
  • 2020-12-08 16:13

    as @Jonny mentioned you can try and detect touch events, this is the solution i currently use

    function isTouchDevice() {
      if (typeof window === 'undefined') return false
      const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ')
      function mq(query) {
        return typeof window !== 'undefined' && window.matchMedia(query).matches
      }
      if ('ontouchstart' in window || (window?.DocumentTouch && document instanceof DocumentTouch)) return true
      const query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('') // include the 'heartz' - https://git.io/vznFH
      return mq(query)
    }
    

    interesting post on detecting touch events

    and another note, Firefox on Ipad uses the same safari user-agent :/

    0 讨论(0)
  • 2020-12-08 16:19

    I would not generally recommend this, and I haven't tested it much (using something similar in production since September 2019), but one way could be to detect the existence of TouchEvent on the client side, and match it with the state of the user agent to account for older iOS versions of iPad:s. YMMV. Likely not very future safe.

    function isIpad() {
        const ua = window.navigator.userAgent;
        if (ua.indexOf('iPad') > -1) {
            return true;
        }
    
        if (ua.indexOf('Macintosh') > -1) {
            try {
                document.createEvent("TouchEvent");
                return true;
            } catch (e) {}
        }
    
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题