在前端编码过程中,我们经常会遇到取得用户浏览器和操作系统的情况。

下面让我们来看看如何使用js代码来取得用户所使用的浏览器:

// 取得浏览器
getBrowse = function () {
    // 不可打乱顺序
    if (navigator.userAgent.indexOf("MSIE" ) > 0) {return "MSIE";}
    if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {return "Firefox" ;}
    if(navigator.userAgent.indexOf("safari" ) > 0 && navigator.userAgent.indexOf("Chrome" ) < 0){
        return "Safari";
    }
    if(navigator.userAgent.indexOf("Chrome" ) > 0){return "Chrome";}
    if (isCamino = navigator.userAgent.indexOf("Camino") > 0) { return "Camino";}
    if (isMozilla = navigator.userAgent.indexOf("Gecko/") > 0) { return "Gecko";}
};

取得操作系统:

// 取得操作系统
detectOS = function() {
    var sUserAgent = navigator.userAgent;
    var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
    var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") 
        || (navigator.platform == "Macintosh" ) || (navigator.platform == "MacIntel" );
    if (isMac) return "Mac" ;
    var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
    if (isUnix) return "Unix" ;
    var isLinux = (String(navigator.platform).indexOf( "Linux") > -1);
    if (isLinux) return "Linux" ;
    if (isWin) {
        var isWin2K = sUserAgent.indexOf("Windows NT 5.0" ) > -1 || sUserAgent.indexOf("Windows 2000" ) > -1;
        if (isWin2K) return "Win2000";
        var isWinXP = sUserAgent.indexOf("Windows NT 5.1" ) > -1 || sUserAgent.indexOf("Windows XP" ) > -1;
        if (isWinXP) return "WinXP";
        var isWin2003 = sUserAgent.indexOf("Windows NT 5.2" ) > -1 || sUserAgent.indexOf("Windows 2003" ) > -1;
        if (isWin2003) return "Win2003";
        var isWinVista= sUserAgent.indexOf("Windows NT 6.0" ) > -1 || sUserAgent.indexOf("Windows Vista" ) > -1;
        if (isWinVista) return "WinVista";
        var isWin7 = sUserAgent.indexOf("Windows NT 6.1" ) > -1 || sUserAgent.indexOf("Windows 7" ) > -1;
        if (isWin7) return "Win7";
    }
    return "other";
};

当有新的浏览器和操作系统后,基于以上代码进行扩展即可。