我知道有很多方法可以检测手机用户(主要是通过检查用户代理)。
但是许多移动浏览器都有所谓的“桌面模式”,它为网站提供了更多的功能环境。
有没有办法只为这些以这种模式浏览的移动用户提供特定功能(例如 jQuery 滑块)?我遇到的真正问题是,本质上,他们的用户代理在两种模式下都是相同的(例如“Opera Mini 9.0.1”),所以从网站管理员的角度来看 - 我怎么知道他们在移动设备上但是以桌面模式浏览网站?
这里是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);
在 Android Chrome 上,“桌面模式”从用户代理中删除“Android”字符串。如果您可以使用 JavaScript,则以下mostly 检测到 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.chrome
和 window.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 视口和捏缩放(不是页面缩放)在 Android 上对于我们的 SPA 来说真的很糟糕(屏幕尺寸不够,因为桌面触摸用户可以使用小窗口)。如果检测操作系统/平台不是问题,那么你可以这样做。
const screenWidth = window.screen.width;
const isMobile = screenWidth <= 480;
const isTablet = screenWidth <= 1024;
可以有几个高端平板电脑,宽度达到1280px;
可以很好测试的代码:
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");
}
这可以通过将可用屏幕宽度与实际屏幕宽度进行比较来完成。后者应该更大 在 2 种情况下.
function isDesktopMode() {
return window.innerWidth > screen.availWidth;
}
返回true,如果
返回false,如果