Skip to content

Instantly share code, notes, and snippets.

@sapienza
Created June 12, 2013 20:11
Show Gist options
  • Select an option

  • Save sapienza/5768695 to your computer and use it in GitHub Desktop.

Select an option

Save sapienza/5768695 to your computer and use it in GitHub Desktop.
Javascript Class to detect browser versions by it's user agent.
var Browser = {
getAgent: function()
{
return navigator.userAgent.toLowerCase();
},
isMac: function(userAgent)
{
var agent = userAgent || this.getAgent();
return !!agent.match(/mac/i);
},
isWin: function(userAgent)
{
var agent = userAgent || this.getAgent();
return !!agent.match(/win/i);
},
isWebKit: function(userAgent)
{
if(this._isWebKit === undefined)
{
var agent = userAgent || this.getAgent();
this._isWebKit = !!agent.match(/AppleWebKit/i);
this.isWebKit = function()
{
return this._isWebKit;
};
}
return this._isWebKit;
},
isSafari2: function(userAgent)
{
if(this._isSafari2 === undefined)
{
if (!this.isWebKit())
{
this._isSafari2 = false;
} else {
var ua = navigator.userAgent.toLowerCase();
var version = parseInt(parseFloat(ua.substring(ua.lastIndexOf('safari/') + 7)), 10);
this._isSafari2 = (version >= 419);
}
this.isSafari2 = function()
{
return this._isSafari2;
};
}
return this._isSafari2;
},
isChrome: function(userAgent)
{
if(this._isChrome === undefined)
{
var agent = userAgent || this.getAgent();
this._isChrome = !!agent.match(/Chrome/i);
this.isChrome = function()
{
return this._isChrome;
};
}
return this._isChrome;
},
isOpera: function(userAgent)
{
var agent = userAgent || this.getAgent();
return !!agent.match(/opera/i);
},
isIE: function(userAgent)
{
var agent = userAgent || this.getAgent();
return !!agent.match(/msie/i);
},
isIEStrict: function(userAgent)
{
var agent = userAgent || this.getAgent();
return agent.match(/msie/i) && !this.isOpera(agent);
},
isIE8: function(userAgent)
{
var agent = userAgent || this.getAgent();
var ie = agent.match(/msie\D*([\.\d]*)/i);
var version = 0;
if (ie && ie[1])
{
version = ie[1];
}
return version >= 8;
},
isFirefox: function(userAgent)
{
var agent = userAgent || this.getAgent();
return !!agent.match(/firefox/i);
},
isiPhone: function(userAgent)
{
var agent = userAgent || this.getAgent();
return !!(this.isWebKit(agent) && agent.match(/iphone/i));
},
isiPad: function(userAgent)
{
var agent = userAgent || this.getAgent();
return !!(this.isWebKit(agent) && agent.match(/ipad/i));
},
isMobile: function(userAgent)
{
var agent = userAgent || this.getAgent();
return this.isWebKit(agent) && (agent.match(/mobile/i));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment