5

我知道有很多方法可以检测手机用户(主要是通过检查用户代理)。

但是很多移动浏览器都有所谓的“桌面模式”,它为网站提供了更多的功能环境。

有没有办法只为这些移动用户提供特定功能(例如 jQuery 滑块),在这种模式下浏览?我遇到的真正问题是,基本上,他们的用户代理在两种模式下都是相同的(例如“Opera Mini 9.0.1”),所以从网站管理员的角度来看 - 我怎么知道他们在移动设备上但是以桌面模式浏览网站?

4

4 回答 4

4

这是 iOS Safari 用户的相关代码。本质上,用户代理在桌面模式下丢失了对 iPhone/iPod/iPad 的引用,但该信息仍然存在于 navigator.platform 中:

var iOSAgent = window.navigator.userAgent.match(/iPhone|iPod|iPad/);
var iOSPlatform = window.navigator.platform && window.navigator.platform.match(/iPhone|iPod|iPad/);
var iOSRequestDesktop = (!iOSAgent && iOSPlatform);
于 2018-09-27T13:54:00.980 回答
3

在 Android Chrome 上,“桌面模式”会从用户代理中删除“Android”字符串。如果可以使用 JavaScript,以下主要检测 Android Chrome 桌面模式:

var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.appVersion)[1], 10); // also matches AppleWebKit
var isGoogle = webkitVer && navigator.vendor.indexOf('Google') === 0;  // Also true for Opera Mobile and maybe others
var isAndroid = isGoogle && userAgent.indexOf('Android') > 0;  // Careful - Firefox and Windows Mobile also have Android in user agent
var androidDesktopMode = !isAndroid && isGoogle && (navigator.platform.indexOf('Linux a') === 0) && 'ontouchstart' in document.documentElement;

它假设带有 ARM 处理器的 Chrome 是 Android。对于在 ARM 上运行 Linux 的用户来说,这个假设肯定是失败的,对于 i686 或 MIPS 等上的 Android 来说是失败的(而且我还无法测试 ChromeOS)。

对于 Windows Mobile,您可以通过检查字符串“WPDesktop;”来检测桌面模式。在用户代理中。

编辑:过去使用的代码window.chromewindow.chrome.webstore一个可靠的测试,但在 Chrome 65 附近的某个地方,您无法再使用这些属性来检测桌面模式。感谢@faks 提供的信息。

编辑 2:我现在强烈建议不要将“桌面模式”视为“移动模式”,但是,这是我的更新意见:

  • 请注意,检测桌面模式的代码确实很脆弱,并且较新的浏览器版本经常会破坏嗅探代码技术

  • 除非您有严重的错误或严重的可用性问题,否则完全不值得一探

  • 如果您没有积极维护代码并针对 Beta 版浏览器进行测试,请永远不要嗅探

  • 我对 iOS 使用以下内容:navigator.vendor.indexOf('Apple') === 0 && 'ontouchstart' in document.body. 我们需要它来为 iPadOS 13 正确设置令人惊讶的糟糕 iOS inputMode(旧的 navigator.platform 技术现在在 iOS 13 Beta 中被破坏)并避免其他输入类型的其他 iOS 可用性错误。我认为您可以检查window.screen.width == 768以嗅探 iPad(即使方向改变也保持不变)。如果 Macbook 推出触控版,嗅探就会中断。

  • 我现在使用以下方法来检测 Android 桌面模式:'ontouchstart' in document.body && navigator.platform.indexOf('Linux a') === 0 && (window.chrome || (window.Intl && Intl.v8BreakIterator)). 可怕的不可靠嗅探,但我们真的需要它,因为 android 视口和捏缩放(不是页面缩放)在我们的 SPA 上确实被打破了(屏幕尺寸不够,因为桌面触摸用户可以使用小窗口)。

于 2017-01-23T00:43:03.680 回答
2

如果检测操作系统/平台不是问题,那么您可以这样做。

const screenWidth = window.screen.width;
const isMobile = screenWidth <= 480;
const isTablet = screenWidth <= 1024;

可以有一些宽度达到1280px的高端平板电脑;

于 2021-10-01T04:24:56.600 回答
0

可以很好地测试的代码:

let screenWidth = window.screen.width;
let isMobile = screenWidth <= 480;

let details = navigator.userAgent;

let regexp = /android|iphone|kindle|ipad/i;

let isMobileDevice = regexp.test(details);

if (isMobileDevice && isMobile) {
    document.write("You are using a Mobile Device");
} else if (isMobile) {
    document.write("You are using Desktop on Mobile"); // the most interesting
} else {
    document.write("You are using Desktop");
}
于 2021-12-12T18:34:08.200 回答