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
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.
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;
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 :/
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;
}