【问题标题】:Wrong (maxTouchPoints) and ('ontouchstart' in document) in Chrome mobile emulation modeChrome 移动仿真模式中的错误 (maxTouchPoints) 和 ('ontouchstart' in document)
【发布时间】:2019-09-13 22:39:30
【问题描述】:

我使用这样的触摸屏设备检测:

if (window.navigator.maxTouchPoints || 'ontouchstart' in document)  
    // handle as mobile device
else
    // handle as desktop

当我在 Chrome 移动仿真中更改屏幕时,maxTouchPoints'ontouchstart' in document 的结果都无法预测。

对于同一个模拟屏幕,它可能返回 maxTouchPoints 等于 0 或 1,'ontouchstart' in document 等于 truefalse

所以,我真的不能做这张支票。
您能推荐一种解决此问题的方法吗?

【问题讨论】:

  • 听起来像一个错误,所以也许你可以在crbug.com 上报告它。至于解决方案,我建议使用真正的模拟器应用程序,并通过网络使用 ADB 将您的桌面 Chrome 连接到其移动 Chrome(它是内置的,或者有启用它的移动应用程序)。

标签: javascript google-chrome-devtools touch emulation


【解决方案1】:

我创建了以下函数来检查是否实际启用了触摸点(例如,使用设备/模拟器上的“启用触摸点按钮”):

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;
}

【讨论】:

  • 必须添加try..catch。否则它会在某些浏览器中崩溃:阻止具有源“ohmydots.com”的框架访问跨域框架。
【解决方案2】:

这个怎么样?

function isTouchscreen() {
  return ("ontouchstart" in window) || (navigator.maxTouchPoints > 0) ? true : false;
}

if (isTouchscreen()) {
  console.log('IS touchscreen');}
else {
  console.log('IS NOT touchscreen');
}

参考:https://developer.mozilla.org/en-US/docs/Web/API/Navigator/maxTouchPoints

【讨论】:

  • MaxTouchPoints 应为小写:navigator.maxTouchPoints > 0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 2015-10-05
  • 2014-05-08
  • 1970-01-01
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多