Search code examples
javascripthtmlcompatibilitybrowser-detection

Browser Detection and Compatibility Checking with Java Script


I am trying to detect browser types and IE compatibility from user agent and redirect accordingly. It works only in IE but not in Firefox and Chrome. I am still looking around the solution and cannot figure out yet.

<html>
<head>
<title>Testing </title>
<script src="UserAgent.js" type="text/javascript"></script>
</head>
<body>
<div id="results">Output</div>
<script type="text/javascript">

if (UserAgent.firefox){
    window.location.href("http://www.yahoo.com");
}

if (UserAgent.compatibilityMode) {
    window.location.href("http://192.168.10.236/iecorrect.html");
} else {
    window.location.href("http://www.apple.com");
}

</script>
</body>
</html>

UserAgent.js

if (typeof jQuery == 'undefined') {
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
}

// Create new object
var UserAgent = {
init: function () {
    // Get the user agent string
    var ua = navigator.userAgent;
    this.compatibilityMode = false;      
    this.firefox = ua.toLowerCase().indexOf("firefox") > -1;
    this.chrome = ua.toLowerCase().indexOf("chrome") > -1

    if (ua.indexOf("MSIE 7.0") > -1) {
        this.compatibilityMode = true;
    }
}
};

// Initialize the object
ieUserAgent.init();

Solution

  • Change your window.loacation.href calls to the below code:

    if (UserAgent.compatibilityMode) {
        window.location.href = "http://192.168.10.236/iecorrect.html";
    } else {
        window.location.href = "http://www.apple.com";
    }
    

    You wrote them like you would write jQuery :)