簡體   English   中英

僅檢測使用“桌面模式”瀏覽器的移動用戶

[英]Detect Only Mobile Users with "Desktop Mode" Browsers

我知道有很多方法可以檢測手機用戶(主要是通過檢查用戶代理)。

但是很多手機瀏覽器都有所謂的“桌面模式”,它為網站提供了更多的功能環境。

有沒有辦法只向這些移動用戶提供特定功能(例如 jQuery 滑塊),在這種模式下瀏覽? 我遇到的真正問題是,本質上,他們的用戶代理在兩種模式下都是相同的(例如“Opera Mini 9.0.1”),所以從網站管理員的角度來看 - 我怎么知道他們在移動設備上但是以桌面模式瀏覽網站?

在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:我現在強烈建議不要將“桌面模式”視為“移動模式”,但這里是我更新的觀點:

  • 請注意,檢測桌面模式的代碼非常脆弱,而較新的瀏覽器版本會經常破壞嗅探代碼技術

  • 除非你有嚴重的錯誤或關鍵的可用性問題,否則完全不值得嗅探

  • 如果您沒有積極維護代碼並針對測試版的瀏覽器進行測試,請不要嗤之以鼻

  • 我在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上真的被破壞了(屏幕尺寸不夠,因為桌面觸摸用戶可以使用小窗口)。

這是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);

如果檢測操作系統/平台不是問題,那么您可以這樣做。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM