I use a touchscreen device detection like this:
if (window.navigator.maxTouchPoints || 'ontouchstart' in document)
// handle as mobile device
else
// handle as desktop
When I change the screen in Chrome mobile emulation the result of both maxTouchPoints
and 'ontouchstart' in document
is unpredictable.
For one and same emulated screen it may return maxTouchPoints
equals to 0 or 1, and 'ontouchstart' in document
equals to true
or false
.
So, I cannot really on this check.
Could you remend a way to fix this?
I use a touchscreen device detection like this:
if (window.navigator.maxTouchPoints || 'ontouchstart' in document)
// handle as mobile device
else
// handle as desktop
When I change the screen in Chrome mobile emulation the result of both maxTouchPoints
and 'ontouchstart' in document
is unpredictable.
For one and same emulated screen it may return maxTouchPoints
equals to 0 or 1, and 'ontouchstart' in document
equals to true
or false
.
So, I cannot really on this check.
Could you remend a way to fix this?
- 1 Sounds like a bug so maybe you could report it on crbug.. As for a solution, I suggest using a real emulator app, and connect your desktop Chrome to its mobile Chrome by using ADB over network (it's either built-in or there are mobile apps that enable it). – woxxom Commented Apr 25, 2019 at 4:34
3 Answers
Reset to default 3I created following function that checks if touch points are actually enabled (for example, using the "enable touch points button" on device/emulator):
function isTouchEventsEnabled() {
// Bug in FireFox+Windows 10, navigator.maxTouchPoints is incorrect when script is running inside frame.
// TBD: report to bugzilla.
const navigator = (window.top || window).navigator;
const maxTouchPoints = Number.isFinite(navigator.maxTouchPoints) ? navigator.maxTouchPoints : navigator.msMaxTouchPoints;
if (Number.isFinite(maxTouchPoints)) {
// Windows 10 system reports that it supports touch, even though it acutally doesn't (ignore msMaxTouchPoints === 256).
return maxTouchPoints > 0 && maxTouchPoints !== 256;
}
return 'ontouchstart' in window;
}
I just upgraded Chrome to version 101.0.4951.67 and now this problem appears.
You may get over it by using
let maxTouchPoints = navigator.maxTouchPoints & 0xFF;
or by using a shim:
let descriptor = navigator.platform === 'Win32' ?
Object.getOwnPropertyDescriptor(Navigator.prototype, 'maxTouchPoints') : null;
if(descriptor && descriptor.get){
Object.defineProperty(Navigator.prototype, 'maxTouchPoints', {
enumerable: true,
configurable: true,
get: function(){
return descriptor.get.call(this) & 0xFF;
}
});
}
How about this?
function isTouchscreen() {
return ("ontouchstart" in window) || (navigator.maxTouchPoints > 0) ? true : false;
}
if (isTouchscreen()) {
console.log('IS touchscreen');}
else {
console.log('IS NOT touchscreen');
}
Reference: https://developer.mozilla/en-US/docs/Web/API/Navigator/maxTouchPoints