如何使用JavaScript 偵測瀏覽器版本和作業系統
問題:
問題:使用時提供的程式碼,瀏覽器偵測在Chrome 和Mozilla 中有效,但在IE6 中失敗。要求是從用戶代理字串中專門提取瀏覽器版本,例如“Firefox/12.0”。
解決方案:var nVer = navigator.appVersion; var nAgt = navigator.userAgent; var browserName = navigator.appName; var fullVersion = '' + parseFloat(navigator.appVersion); var majorVersion = parseInt(navigator.appVersion, 10); var nameOffset, verOffset, ix; // Determine browser name and version based on user agent string if ((verOffset = nAgt.indexOf("OPR")) != -1) { // Opera browserName = "Opera"; fullVersion = nAgt.substring(verOffset + 4); if ((verOffset = nAgt.indexOf("Version")) != -1) { fullVersion = nAgt.substring(verOffset + 8); } } else if ((verOffset = nAgt.indexOf("Edg")) != -1) { // Microsoft Edge browserName = "Microsoft Edge"; fullVersion = nAgt.substring(verOffset + 4); } else if ((verOffset = nAgt.indexOf("MSIE")) != -1) { // Microsoft Internet Explorer browserName = "Microsoft Internet Explorer"; fullVersion = nAgt.substring(verOffset + 5); } else if ((verOffset = nAgt.indexOf("Chrome")) != -1) { // Chrome browserName = "Chrome"; fullVersion = nAgt.substring(verOffset + 7); } else if ((verOffset = nAgt.indexOf("Safari")) != -1) { // Safari browserName = "Safari"; fullVersion = nAgt.substring(verOffset + 7); if ((verOffset = nAgt.indexOf("Version")) != -1) { fullVersion = nAgt.substring(verOffset + 8); } } else if ((verOffset = nAgt.indexOf("Firefox")) != -1) { // Firefox browserName = "Firefox"; fullVersion = nAgt.substring(verOffset + 8); } else if ( (nameOffset = nAgt.lastIndexOf(" ") + 1) < (verOffset = nAgt.lastIndexOf("/")) ) { browserName = nAgt.substring(nameOffset, verOffset); fullVersion = nAgt.substring(verOffset + 1); if (browserName.toLowerCase() == browserName.toUpperCase()) { browserName = navigator.appName; } } // Trim fullVersion string to remove semicolon or space if present if ((ix = fullVersion.indexOf(";")) != -1) { fullVersion = fullVersion.substring(0, ix); } if ((ix = fullVersion.indexOf(" ")) != -1) { fullVersion = fullVersion.substring(0, ix); } // Convert fullVersion to number and fall back to navigator.appVersion if conversion fails majorVersion = parseInt("" + fullVersion, 10); if (isNaN(majorVersion)) { fullVersion = "" + parseFloat(navigator.appVersion); majorVersion = parseInt(navigator.appVersion, 10); } // Display browser and version information document.write( "" + 'Browser name = ' + browserName + "<br>" + 'Full version = ' + fullVersion + "<br>" + 'Major version = ' + majorVersion + "<br>" + 'navigator.appName = ' + navigator.appName + "<br>" + 'navigator.userAgent = ' + navigator.userAgent + "<br>" );
以上是如何使用 JavaScript 可靠地偵測瀏覽器版本和作業系統?的詳細內容。更多資訊請關注PHP中文網其他相關文章!