如何检测移动设备或桌面设备,避免被 Chrome 开发者工具欺骗。

3

我想检测用户在我的应用程序上使用移动设备的情况。

通常,我们会通过使用用户代理或可触摸屏幕来进行检测,但是在开发工具中的Chrome移动模式会更改这两个选项。

您有什么办法可以检测移动设备或桌面设备,并且不会被Chrome开发工具欺骗吗?


1
由于可能存在的设备类型范围,区分移动/桌面(例如平板电脑是移动设备还是桌面设备)并不重要。这取决于您想要区分的原因,但通常是为了布局(因此屏幕大小/纵横比通常是您需要查找的内容),或者为了输入功能(某些设备是混合触摸/指针能力)。 - Dave Meehan
对我来说,移动设备/平板电脑并不重要,我关注的主要是(桌面/无桌面)。 在比例搜索中,我也会被“欺骗”,因为Chrome中的移动模式使用真实设备尺寸。 - Matan Shushan
1
你并没有被“欺骗”,这更多地与现实有关,即设备类型已不再区分,而是取决于其功能。用户代理只是一个提示,机器人误认为自己是浏览器是很常见的。也许如果你能描述一下你想要区分的目的,会有所帮助? - Dave Meehan
3个回答

2

与其根据设备类型进行选择,您可以检查操作系统。 这里 是可以使用的可能值列表。

windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];
android = "Android";
typeOfOS = window.navigator.platform;

if (windowsPlatforms.includes(typeOfOS)) {
     //do for windows
} else if(typeOfOS === android){
     //do for android
}

有用但不建议使用。特征检测才是正确的方法。 - Jake

0
一种在不检查操作系统或窗口大小的情况下进行的方法是通过特征检测来检查触摸事件,就像这样:
const isMobile = 'ontouchstart' in window || navigator.maxTouchPoints > 0;

这将返回一个布尔值,用于判断用户是否在移动设备上,而不会被在移动设备上使用桌面视图欺骗。

0
你可以在CSS中实现。你可以使用@media来判断屏幕尺寸是否小于通常的桌面尺寸,从而使你的应用程序具有响应式设计。看一下这段代码:

body {
  --background-image: url('https://thumbs.dreamstime.com/b/vertical-banner-template-hands-typing-computer-office-supplies-distance-education-e-learning-obtaining-university-156390588.jpg');
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-image: var(--background-image);
  background-size: 100vw 100vh;
  z-index: -1000;
}

#submit-form {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 180px;
  width: 300px;
  background-color: white;
  border-radius: 10px;
  border: 2px dashed;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  z-index: 1000;
}

#email-input {
  height: 30px;
  width: 220px;
  border-radius: 10px;
}

#submit-button {
  height: 30px;
  width: 80px;
  border-radius: 10px;
  background-color: lightgreen;
  border: 1px dashed;
}

@media all and (min-width: 1000px) {
  body {
    background-image: url('https://img.freepik.com/free-vector/online-education-students-view-lessons-through-mobile-devices-during-distance-learning_178888-361.jpg?w=2000');
  }
  #submit-form {
    height: 250px;
    width: 500px;
  }
  #email-input {
    height: 50px;
    width: 300px;
    border-radius: 10px;
  }
}

在这里,我先为移动设备设计站点样式,然后检查用户是否在桌面上,如果是,则再次使网站具有响应性。
这只是样式部分,但是如果您想在JavaScript中检测它怎么办?
您可以使用一个简单的函数来实现:

function findUserDevice() {
  const isOnMobile = false;

  if(window.innerWidth < window.innerHeight) {
    isOnMobile = true;
  }
  return isOnMobile;
}

这是我通常使用的,希望对你有所帮助!


3
因为手机分辨率每年与台式机重叠的部分越来越多,更不用说平板电脑了,所以这并不是非常可靠的。 - Max Tuzenko
这是正确的,一个更好的解决方案是确切地知道用户使用的设备。这通常是我通过不断更新来实现的。然而,为每种类型的设备进行优化将会相当困难... - G Jeswin
@GJeswin 不,那根本不是更好的解决方案。最好的解决方案是根据您依赖的特定参数进行调整,例如输入方法(触摸 vs 鼠标,也许还包括主要输入方法),视口大小或其他。 - Jake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接