alias51
alias51

Reputation: 8648

What's the easiest way to redirect unsupported browsers?

I am coding a site that supports IE9, Firefox 23, Chrome 29 and safari 5.1.

Rather than graceful depreciation, I simply want to redirect all other browsers to a separate webpage that says "Sorry buddy. Time to be a man and get a real browser.".

What's the simplest way to do this with the least amount of code?

Upvotes: 2

Views: 3380

Answers (2)

adeneo
adeneo

Reputation: 318322

Feature detection is the way to go, and not browser sniffing, but to provide you with the answer you seem to be looking for, I cooked up this :

var browser = (function(){
    var ua = navigator.userAgent, 
        M  = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [],
        tem;

    if(/trident/i.test(M[1])){
        tem =  /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
        return ['ie', (tem[1] || '')];
    }
    M = M[2] ? [M[1].toLowerCase(), M[2]]:[navigator.appName.toLowerCase(), navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/([\.\d]+)/i))!= null) M[2] = tem[1];
    return M;
})();

var supported = {
    'ie' : 9,
    'chrome' : 29,
    'safari' : 5.1
}

if (supported[browser[0]] <= (browser[0]=='safari' ? parseFloat(browser[1]) : parseInt(browser[1],10))) {
    alert('Your browser is OK !');
}else{
    window.location.href = 'http://browsehappy.com/';
}

It's untested in all browsers but the latest chrome, you'll have to test it yourself, and tweak it to your needs, but it should return an array with the browsername and browserversion that you can check to see if it matches your requirements.

And again, feature detection is generally the way to go, browser sniffing isn't.

Upvotes: 5

agconti
agconti

Reputation: 18123

Try Modernizer:

Its a really easy js plugin that allows you to detect, redirect, and otherwise support users coming from less then current browsers. The link above should give you all you need to know.

From thier site:

Modernizr makes it easy for you to write conditional JavaScript and CSS to handle each situation, whether a browser supports a feature or not. It’s perfect for doing progressive enhancement easily.

Upvotes: 1

Related Questions