Getting a browser's name client-side - javascript

Is there any object or method that returns data about the browser, client-side?
For example, I need to detect if the browser is IE (Interner Explorer). Following is the code snippet.
function isInternetExplorer()
{
if(navigator.appName.indexOf("Microsoft Internet Explorer") != -1)
{
return true;
}
return false;
}
Is there a better way?

JavaScript side - you can get browser name like these ways...
if(window.navigator.appName == "") OR if(window.navigator.userAgent == "")

This is pure JavaScript solution. Which I was required.
I tried on different browsers. It is working fine. Hope it helps.
How do I detect the browser name ?
You can use the navigator.appName and navigator.userAgent properties. The userAgent property is more reliable than appName because, for example, Firefox (and some other browsers) may return the string "Netscape" as the value of navigator.appName for compatibility with Netscape Navigator.
Note, however, that navigator.userAgent may be spoofed, too – that is, clients may substitute virtually any string for their userAgent. Therefore, whatever we deduce from either appName or userAgent should be taken with a grain of salt.
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;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
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 the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>');
From the source javascripter.net

EDIT: Since the answer is not valid with newer versions of jquery As jQuery.browser is deprecated in ver 1.9, So Use Jquery Migrate Plugin for that matter.
Original Answer
jQuery.browser
jQuery.browser
and
jQuery.browser.version
is your way to go...

I found a purely Javascript solution here that seems to work for major browsers for both PC and Mac. I tested it in BrowserStack for both platforms and it works like a dream. The Javascript solution posted in this thread by Jason D'Souza is really nice because it gives you a lot of information about the browser, but it has an issue identifying Edge which seems to look like Chrome to it. His code could probably be modified a bit with this solution to make it work for Edge too. Here is the snippet of code I found:
var browser = (function (agent) {
switch (true) {
case agent.indexOf("edge") > -1: return "edge";
case agent.indexOf("edg") > -1: return "chromium based edge (dev or canary)";
case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
case agent.indexOf("chrome") > -1 && !!window.chrome: return "chrome";
case agent.indexOf("trident") > -1: return "ie";
case agent.indexOf("firefox") > -1: return "firefox";
case agent.indexOf("safari") > -1: return "safari";
default: return "other";
}
})(window.navigator.userAgent.toLowerCase());
console.log(window.navigator.userAgent.toLowerCase() + "\n" + browser);
UPDATED
Here is a better version from BSlink's answer which has a few problems. There are too many edits in the queue for me to submit one in his answer so I'm editing my own answer to share the corrections:
const agent = window.navigator.userAgent.toLowerCase();
const browser =
agent.indexOf('edge') > -1 ? 'edge'
: agent.indexOf('edg') > -1 ? 'chromium based edge'
: agent.indexOf('opr') > -1 && window.opr ? 'opera'
: agent.indexOf('chrome') > -1 && window.chrome ? 'chrome'
: agent.indexOf('trident') > -1 ? 'ie'
: agent.indexOf('firefox') > -1 ? 'firefox'
: agent.indexOf('safari') > -1 ? 'safari'
: 'other';
console.log(`${agent}\n${browser}`);

In c# you your browser name using:
System.Web.HttpBrowserCapabilities browser = Request.Browser;
For details see a link.
http://msdn.microsoft.com/en-us/library/3yekbd5b%28v=vs.100%29.aspx
and in Client side:
JQuery:
jQuery.browser
For details see a link:
http://api.jquery.com/jQuery.browser/

I liked Sintrias's answer but I wanted to uppdate a bit with a slightly more modern syntax.
const userAgent = window.navigator.userAgent.toLowerCase();
const browser =
userAgent.indexOf('edge') > -1 ? 'edge'
: userAgent.indexOf('edg') > -1 ? 'chromium based edge'
: userAgent.indexOf('opr') > -1 && !!window.opr ? 'opera'
: userAgent.indexOf('chrome') > -1 && !!window.chrome ? 'chrome'
: userAgent.indexOf('trident') > -1 ? 'ie'
: userAgent.indexOf('firefox') > -1 ? 'firefox'
: userAgent.indexOf('safari') > -1 ? 'safari'
: 'other';
console.log(`${userAgent.toLowerCase()}\n${browser}`);

The browser discloses it in navigator.userAgent. If you're using jQuery, you're better off using jQuery.browser as #Rab Nawaz said. However, as the API documentation says, it's better to check for feature support if possible. Quoting the documentation:
We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.
Here is a code example:
function isIE() {
if (window.jQuery) {
return jQuery.browser.msie || false;
} else {
// adapted from jQuery's source:
return navigator.userAgent.toLowerCase().indexOf('msie') >= 0;
}
}

This is answered in
How to detect Safari, Chrome, IE, Firefox and Opera browser?
Check this fiddle.
Hope this helps.

It's all about what you really want to do, but in times to come and right now, the best way is avoid browser detection and check for features. like Canvas, Audio, WebSockets, etc through simple javascript calls or in your CSS, for me your best approach is use a tool like ModernizR:
Unlike with the traditional—but highly unreliable—method of doing “UA sniffing,” which is detecting a browser by its (user-configurable) navigator.userAgent property, Modernizr does actual feature detection to reliably discern what the various browsers can and cannot do.
If using CSS, you can do this:
.no-js .glossy,
.no-cssgradients .glossy {
background: url("images/glossybutton.png");
}
.cssgradients .glossy {
background-image: linear-gradient(top, #555, #333);
}
as it will load and append all features as a class name in the <html> element and you will be able to do as you wish in terms of CSS.
And you can even load files upon features, for example, load a polyfill js and css if the browser does not have native support
Modernizr.load([
// Presentational polyfills
{
// Logical list of things we would normally need
test : Modernizr.fontface && Modernizr.canvas && Modernizr.cssgradients,
// Modernizr.load loads css and javascript by default
nope : ['presentational-polyfill.js', 'presentational.css']
},
// Functional polyfills
{
// This just has to be truthy
test : Modernizr.websockets && window.JSON,
// socket-io.js and json2.js
nope : 'functional-polyfills.js',
// You can also give arrays of resources to load.
both : [ 'app.js', 'extra.js' ],
complete : function () {
// Run this after everything in this group has downloaded
// and executed, as well everything in all previous groups
myApp.init();
}
},
// Run your analytics after you've already kicked off all the rest
// of your app.
'post-analytics.js'
]);
a simple example of requesting features from javascript:
http://jsbin.com/udoyic/1

This code will return "browser" and "browserVersion"
Works on 95% of 80+ browsers
var geckobrowsers;
var browser = "";
var browserVersion = 0;
var agent = navigator.userAgent + " ";
if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("like Gecko") != -1){
geckobrowsers = agent.substring(agent.indexOf("like Gecko")+10).substring(agent.substring(agent.indexOf("like Gecko")+10).indexOf(") ")+2).replace("LG Browser", "LGBrowser").replace("360SE", "360SE/");
for(i = 0; i < 1; i++){
geckobrowsers = geckobrowsers.replace(geckobrowsers.substring(geckobrowsers.indexOf("("), geckobrowsers.indexOf(")")+1), "");
}
geckobrowsers = geckobrowsers.split(" ");
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("/") == -1)geckobrowsers[i] = "Chrome";
if(geckobrowsers[i].indexOf("/") != -1)geckobrowsers[i] = geckobrowsers[i].substring(0, geckobrowsers[i].indexOf("/"));
}
if(geckobrowsers.length < 4){
browser = geckobrowsers[0];
} else {
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("Chrome") == -1 && geckobrowsers[i].indexOf("Safari") == -1 && geckobrowsers[i].indexOf("Mobile") == -1 && geckobrowsers[i].indexOf("Version") == -1)browser = geckobrowsers[i];
}
}
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Gecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).substring(0, agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Clecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).substring(0, agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0"){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(";"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 == agent.length-1){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ")[agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ").length-1];
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 != agent.length-1){
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") != -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf("/"));
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") == -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf(" "));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(0, 6) == "Opera/"){
browser = "Opera";
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") != -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(";"));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") == -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(")"));
} else if(agent.substring(0, agent.indexOf("/")) != "Mozilla" && agent.substring(0, agent.indexOf("/")) != "Opera"){
browser = agent.substring(0, agent.indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else {
browser = agent;
}
alert(browser + " v" + browserVersion);

You can also get an array of brands that is used by user using the following way:
let browser = window.navigator.userAgentData.brands;
console.log('browser', browser);

Based on is.js you can write a helper file for getting browser name like this-
const Browser = {};
const vendor = (navigator && navigator.vendor || '').toLowerCase();
const userAgent = (navigator && navigator.userAgent || '').toLowerCase();
Browser.getBrowserName = () => {
if(isOpera()) return 'opera'; // Opera
else if(isChrome()) return 'chrome'; // Chrome
else if(isFirefox()) return 'firefox'; // Firefox
else if(isSafari()) return 'safari'; // Safari
else if(isInternetExplorer()) return 'ie'; // Internet Explorer
}
// Start Detecting browser helpers functions
function isOpera() {
const isOpera = userAgent.match(/(?:^opera.+?version|opr)\/(\d+)/);
return isOpera !== null;
}
function isChrome() {
const isChrome = /google inc/.test(vendor) ? userAgent.match(/(?:chrome|crios)\/(\d+)/) : null;
return isChrome !== null;
}
function isFirefox() {
const isFirefox = userAgent.match(/(?:firefox|fxios)\/(\d+)/);
return isFirefox !== null;
}
function isSafari() {
const isSafari = userAgent.match(/version\/(\d+).+?safari/);
return isSafari !== null;
}
function isInternetExplorer() {
const isInternetExplorer = userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);
return isInternetExplorer !== null;
}
// End Detecting browser helpers functions
export default Browser;
And just import this file where you need.
import Browser from './Browser.js';
const userBrowserName = Browser.getBrowserName() // return your browser name
// opera | chrome | firefox | safari | ie

Related

javascript - How to detect what browser is using by a user when viewing a document? [duplicate]

I have 5 addons/extensions for Firefox, Chrome, Internet Explorer(IE), Opera, and Safari.
How can I correctly recognize the user browser and redirect (once an install button has been clicked) to download the corresponding addon?
Googling for browser reliable detection often results in checking the User agent string. This method is not reliable, because it's trivial to spoof this value.
I've written a method to detect browsers by duck-typing.
Only use the browser detection method if it's truly necessary, such as showing browser-specific instructions to install an extension. Use feature detection when possible.
Demo: https://jsfiddle.net/6spj1059/
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
// Internet Explorer 6-11
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 79
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Edge (based on chromium) detection
var isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1);
// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isEdge: ' + isEdge + '<br>';
output += 'isEdgeChromium: ' + isEdgeChromium + '<br>';
output += 'isBlink: ' + isBlink + '<br>';
document.body.innerHTML = output;
Analysis of reliability
The previous method depended on properties of the rendering engine (-moz-box-sizing and -webkit-transform) to detect the browser. These prefixes will eventually be dropped, so to make detection even more robust, I switched to browser-specific characteristics:
Internet Explorer: JScript's Conditional compilation (up until IE9) and document.documentMode.
Edge: In Trident and Edge browsers, Microsoft's implementation exposes the StyleMedia constructor. Excluding Trident leaves us with Edge.
Edge (based on chromium): The user agent include the value "Edg/[version]" at the end (ex: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.16 Safari/537.36 Edg/80.0.361.9").
Firefox: Firefox's API to install add-ons: InstallTrigger
Chrome: The global chrome object, containing several properties including a documented chrome.webstore object.
Update 3 chrome.webstore is deprecated and undefined in recent versions
Safari: A unique naming pattern in its naming of constructors. This is the least durable method of all listed properties and guess what? In Safari 9.1.3 it was fixed. So we are checking against SafariRemoteNotification, which was introduced after version 7.1, to cover all Safaris from 3.0 and upwards.
Opera: window.opera has existed for years, but will be dropped when Opera replaces its engine with Blink + V8 (used by Chromium).
Update 1: Opera 15 has been released, its UA string looks like Chrome, but with the addition of "OPR". In this version the chrome object is defined (but chrome.webstore isn't). Since Opera tries hard to clone Chrome, I use user agent sniffing for this purpose.
Update 2: !!window.opr && opr.addons can be used to detect Opera 20+ (evergreen).
Blink: CSS.supports() was introduced in Blink once Google switched on Chrome 28. It's of course, the same Blink used in Opera.
Successfully tested in:
Firefox 0.8 - 61
Chrome 1.0 - 71
Opera 8.0 - 34
Safari 3.0 - 10
IE 6 - 11
Edge - 20-42
Edge Dev - 80.0.361.9
Updated in November 2016 to include detection of Safari browsers from 9.1.3 and upwards
Updated in August 2018 to update the latest successful tests on chrome, firefox IE and edge.
Updated in January 2019 to fix chrome detection (because of the window.chrome.webstore deprecation) and include the latest successful tests on chrome.
Updated in December 2019 to add Edge based on Chromium detection (based on the #Nimesh comment).
You can try following way to check Browser version.
<!DOCTYPE html>
<html>
<body>
<p>What is the name(s) of your browser?</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 )
{
alert('Opera');
}
else if(navigator.userAgent.indexOf("Edg") != -1 )
{
alert('Edge');
}
else if(navigator.userAgent.indexOf("Chrome") != -1 )
{
alert('Chrome');
}
else if(navigator.userAgent.indexOf("Safari") != -1)
{
alert('Safari');
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
alert('Firefox');
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
alert('IE');
}
else
{
alert('unknown');
}
}
</script>
</body>
</html>
And if you need to know only IE Browser version then you can follow below code. This code works well for version IE6 to IE11
<!DOCTYPE html>
<html>
<body>
<p>Click on Try button to check IE Browser version.</p>
<button onclick="getInternetExplorerVersion()">Try it</button>
<p id="demo"></p>
<script>
function getInternetExplorerVersion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
var rv = -1;
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
{
if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
//For IE 11 >
if (navigator.appName == 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
alert(rv);
}
}
else {
alert('otherbrowser');
}
}
else {
//For < IE11
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
}
return false;
}}
</script>
</body>
</html>
Here are several prominent libraries that handle browser detection as of Dec 2019.
Bowser by lancedikson - 4,065★s - Last updated Oct 2, 2019 - 4.8KB
var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
" v" + result.parsedResult.browser.version +
" on " + result.parsedResult.os.name);
<script src="https://unpkg.com/bowser#2.7.0/es5.js"></script>
*supports Edge based on Chromium
Platform.js by bestiejs - 2,550★s - Last updated Apr 14, 2019 - 5.9KB
console.log(platform);
document.write("You are using " + platform.name +
" v" + platform.version +
" on " + platform.os);
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB
console.log($.browser)
document.write("You are using " + $.browser.name +
" v" + $.browser.versionNumber +
" on " + $.browser.platform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
Detect.js (Archived) by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB
var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
" v" + result.browser.version +
" on " + result.os.family);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B
console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
" v" + BrowserDetect.version +
" on " + BrowserDetect.OS);
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
Notable Mentions:
WhichBrowser - 1,355★s - Last updated Oct 2, 2018
Modernizr - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.
Further Reading
Stack Overflow - Browser detection in JavaScript?
Stack Overflow - How can you detect the version of a browser?
I know it may be overkill to use a lib for that, but just to enrich the thread, you could check is.js way of doing this:
is.firefox();
is.ie(6);
is.not.safari();
In case anyone finds this useful, I've made Rob W's answer into a function that returns the browser string rather than having multiple variables floating about. Since the browser also can't really change without loading all over again, I've made it cache the result to prevent it from needing to work it out the next time the function is called.
/**
* Gets the browser name or returns an empty string if unknown.
* This function also caches the result to provide for any
* future calls this function has.
*
* #returns {string}
*/
var browser = function() {
// Return cached result if avalible, else get result then cache it.
if (browser.prototype._cachedResult)
return browser.prototype._cachedResult;
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;
return browser.prototype._cachedResult =
isOpera ? 'Opera' :
isFirefox ? 'Firefox' :
isSafari ? 'Safari' :
isChrome ? 'Chrome' :
isIE ? 'IE' :
isEdge ? 'Edge' :
isBlink ? 'Blink' :
"Don't know";
};
console.log(browser());
Short variant (update 10 july 2020 mobile browser detection fix)
var browser = (function() {
var test = function(regexp) {return regexp.test(window.navigator.userAgent)}
switch (true) {
case test(/edg/i): return "Microsoft Edge";
case test(/trident/i): return "Microsoft Internet Explorer";
case test(/firefox|fxios/i): return "Mozilla Firefox";
case test(/opr\//i): return "Opera";
case test(/ucbrowser/i): return "UC Browser";
case test(/samsungbrowser/i): return "Samsung Browser";
case test(/chrome|chromium|crios/i): return "Google Chrome";
case test(/safari/i): return "Apple Safari";
default: return "Other";
}
})();
console.log(browser)
Typescript version:
export enum BROWSER_ENUM {
EDGE ,
INTERNET_EXPLORER ,
FIRE_FOX ,
OPERA ,
UC_BROWSER ,
SAMSUNG_BROWSER ,
CHROME ,
SAFARI ,
UNKNOWN ,
}
const testUserAgent = (regexp: RegExp): boolean => regexp.test(window.navigator.userAgent);
function detectBrowser(): BROWSER_ENUM {
switch (true) {
case testUserAgent(/edg/i): return BROWSER_ENUM.EDGE;
case testUserAgent(/trident/i): return BROWSER_ENUM.INTERNET_EXPLORER;
case testUserAgent(/firefox|fxios/i): return BROWSER_ENUM.FIRE_FOX;
case testUserAgent(/opr\//i): return BROWSER_ENUM.OPERA;
case testUserAgent(/ucbrowser/i): return BROWSER_ENUM.UC_BROWSER;
case testUserAgent(/samsungbrowser/i): return BROWSER_ENUM.SAMSUNG_BROWSER;
case testUserAgent(/chrome|chromium|crios/i): return BROWSER_ENUM.CHROME;
case testUserAgent(/safari/i): return BROWSER_ENUM.SAFARI;
default: return BROWSER_ENUM.UNKNOWN;
}
}
export const BROWSER: BROWSER_ENUM = detectBrowser();
export const IS_FIREFOX = BROWSER === BROWSER_ENUM.FIRE_FOX;
Functional algorithm, just for fun:
var BROWSER = new Array(
["Microsoft Edge", /edg/i],
["Microsoft Internet Explorer", /trident/i],
["Mozilla Firefox", /firefox|fxios/i],
["Opera", /opr\//i],
["UC Browser", /ucbrowser/i],
["Samsung Browser", /samsungbrowser/i],
["Google Chrome", /chrome|chromium|crios/i],
["Apple Safari", /safari/i],
["Unknown", /.+/i],
).find(([, value]) => value.test(window.navigator.userAgent)).shift();
No idea if it is useful to anyone but here is a variant that would make TypeScript happy:
export function getBrowser() {
// Opera 8.0+
if ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0) {
return 'opera';
}
// Firefox 1.0+
if (typeof window["InstallTrigger"] !== 'undefined') {
return 'firefox';
}
// Safari 3.0+ "[object HTMLElementConstructor]"
if (/constructor/i.test(window["HTMLElement"]) || (function(p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof window["safari"] !== 'undefined' && window["safari"].pushNotification))) {
return 'safari';
}
// Internet Explorer 6-11
if (/*#cc_on!#*/false || !!document["documentMode"]) {
return 'ie';
}
// Edge 20+
if (!(/*#cc_on!#*/false || !!document["documentMode"]) && !!window["StyleMedia"]) {
return 'edge';
}
// Chrome 1+
if (!!window["chrome"] && !!window["chrome"].webstore) {
return 'chrome';
}
// Blink engine detection
if (((!!window["chrome"] && !!window["chrome"].webstore) || ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0)) && !!window["CSS"]) {
return 'blink';
}
}
Thank you, everybody. I tested the code snippets here on the recent browsers: Chrome 55, Firefox 50, IE 11 and Edge 38, and I came up with the following combination that worked for me for all of them. I'm sure it can be improved, but it's a quick solution for whoever needs:
var browser_name = '';
isIE = /*#cc_on!#*/false || !!document.documentMode;
isEdge = !isIE && !!window.StyleMedia;
if(navigator.userAgent.indexOf("Chrome") != -1 && !isEdge)
{
browser_name = 'chrome';
}
else if(navigator.userAgent.indexOf("Safari") != -1 && !isEdge)
{
browser_name = 'safari';
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
browser_name = 'firefox';
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
browser_name = 'ie';
}
else if(isEdge)
{
browser_name = 'edge';
}
else
{
browser_name = 'other-browser';
}
$('html').addClass(browser_name);
It adds a CSS class to the HTML, with the name of the browser.
Here's a 2016 adjusted version of Rob's answer, including Microsoft Edge and detection of Blink:
(edit: I updated Rob's answer above with this information.)
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;
/* Results: */
console.log("isOpera", isOpera);
console.log("isFirefox", isFirefox);
console.log("isSafari", isSafari);
console.log("isIE", isIE);
console.log("isEdge", isEdge);
console.log("isChrome", isChrome);
console.log("isBlink", isBlink);
The beauty of this approach is that it relies on browser engine properties, so it covers even derivative browsers, such as Yandex or Vivaldi, which are practically compatible with the major browsers whose engines they use. The exception is Opera, which relies on user agent sniffing, but today (i.e. ver. 15 and up) even Opera is itself only a shell for Blink.
You can use try and catch to use the different browser error messages.
IE and edge were mixed up, but I used the duck typing from Rob W (based on this project here: https://www.khanacademy.org/computer-programming/i-have-opera/2395080328).
var getBrowser = function() {
try {
var e;
var f = e.width;
} catch(e) {
var err = e.toString();
if(err.indexOf("not an object") !== -1) {
return "safari";
} else if(err.indexOf("Cannot read") !== -1) {
return "chrome";
} else if(err.indexOf("e is undefined") !== -1) {
return "firefox";
} else if(err.indexOf("Unable to get property 'width' of undefined or null reference") !== -1) {
if(!(false || !!document.documentMode) && !!window.StyleMedia) {
return "edge";
} else {
return "IE";
}
} else if(err.indexOf("cannot convert e into object") !== -1) {
return "opera";
} else {
return undefined;
}
}
};
If you need to know what is the numeric version of some particular browser you can use the following snippet. Currently it will tell you the version of Chrome/Chromium/Firefox:
var match = $window.navigator.userAgent.match(/(?:Chrom(?:e|ium)|Firefox)\/([0-9]+)\./);
var ver = match ? parseInt(match[1], 10) : 0;
Detecting Browsers on Desktop and Mobile : Edge, Opera, Chrome, Safari, Firefox, IE
I did some changes in #nimesh code now it is working for Edge also,
and Opera issue fixed:
function getBrowserName() {
if ( navigator.userAgent.indexOf("Edge") > -1 && navigator.appVersion.indexOf('Edge') > -1 ) {
return 'Edge';
}
else if( navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf('OPR') != -1 )
{
return 'Opera';
}
else if( navigator.userAgent.indexOf("Chrome") != -1 )
{
return 'Chrome';
}
else if( navigator.userAgent.indexOf("Safari") != -1)
{
return 'Safari';
}
else if( navigator.userAgent.indexOf("Firefox") != -1 )
{
return 'Firefox';
}
else if( ( navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true ) ) //IF IE > 10
{
return 'IE';
}
else
{
return 'unknown';
}
}
Thanks #nimesh user:2063564
There is also a less "hacky" method which works for all popular browsers.
Google has included a browser-check in their Closure Library. In particular, have a look at goog.userAgent and goog.userAgent.product. In this way, you are also up to date if something changes in the way the browsers present themselves (given that you always run the latest version of the closure compiler.)
Detecting Browser and Its version
This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.
The data shown in the image above is not sufficient for detecting all the browsers e.g. userAgent of Firefox will have Fxios as a keyword rather than Firefox.
A few changes are also done to detect browsers like Edge and UCBrowser
The code is currently tested for the following browsers by changing userAgent with the help of dev-tools (How to change userAgent):
FireFox
Chrome
IE
Edge
Opera
Safari
UCBrowser
getBrowser = () => {
const userAgent = navigator.userAgent;
let browser = "unkown";
// Detect browser name
browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;
// detect browser version
switch (browser) {
case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
// IE version is mapped using trident version
// IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
default: return `unknown/0.0.0.0`;
}
}
browserVersion = (userAgent,regex) => {
return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}
console.log(getBrowser());
UAParser is one of the JavaScript Library to identify browser, engine, OS, CPU, and device type/model from userAgent string.
There's an CDN available. Here, I have included a example code to detect browser using UAParser.
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/ua-parser-js#0/dist/ua-parser.min.js"></script>
<script type="text/javascript">
var parser = new UAParser();
var result = parser.getResult();
console.log(result.browser); // {name: "Chromium", version: "15.0.874.106"}
</script>
</head>
<body>
</body>
</html>
Now you can use the value of result.browser to conditionally program your page.
Source Tutorial: How to detect browser, engine, OS, CPU, and device using JavaScript?
You can use Detect-browser.js, JavaScript library that detects and prints an object of browser information including browser language/name, user agent, device type, user OS, referer, online/0ffline, user timezone, screen resolution, and cookie enabled.
Get it from here detect-browser.js
it will give you something like that:
Here is my customized solution.
const inBrowser = typeof window !== 'undefined'
const UA = inBrowser && window.navigator.userAgent.toLowerCase()
const isIE =
UA && /; msie|trident/i.test(UA) && !/ucbrowser/i.test(UA).test(UA)
const isEdge = UA && /edg/i.test(UA)
const isAndroid = UA && UA.indexOf('android') > 0
const isIOS = UA && /iphone|ipad|ipod|ios/i.test(UA)
const isChrome =
UA &&
/chrome|crios/i.test(UA) &&
!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(UA)
const isGoogleBot = UA && /googlebot/i.test(UA)
const isChromium = UA && /chromium/i.test(UA)
const isUcBrowser = UA && /ucbrowser/i.test(UA)
const isSafari =
UA &&
/safari/i.test(UA) &&
!/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i.test(UA)
const isFirefox = UA && /firefox|fxios/i.test(UA) && !/seamonkey/i.test(UA)
const isOpera = UA && /opr|opera/i.test(UA)
const isMobile =
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
const isSamsung = UA && /samsungbrowser/i.test(UA)
const isIPad = UA && /ipad/.test(UA)
const isIPhone = UA && /iphone/.test(UA)
const isIPod = UA && /ipod/.test(UA)
console.log({
UA,
isAndroid,
isChrome,
isChromium,
isEdge,
isFirefox,
isGoogleBot,
isIE,
isMobile,
isIOS,
isIPad,
isIPhone,
isIPod,
isOpera,
isSafari,
isSamsung,
isUcBrowser,
}
}
Chrome & Edge introduced a new User-Agent Client Hints API for this:
navigator.userAgentData.brands.map(item => item.brand).includes('Google Chrome')
Firefox & Safari don't support it yet unfortunately.
var BrowserDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
searchString: function (data) {
for (var i = 0; i < data.length; i++) {
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) !== -1) {
return data[i].identity;
}
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index === -1) {
return;
}
var rv = dataString.indexOf("rv:");
if (this.versionSearchString === "Trident" && rv !== -1) {
return parseFloat(dataString.substring(rv + 3));
} else {
return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
}
},
dataBrowser: [
{string: navigator.userAgent, subString: "Edge", identity: "MS Edge"},
{string: navigator.userAgent, subString: "MSIE", identity: "Explorer"},
{string: navigator.userAgent, subString: "Trident", identity: "Explorer"},
{string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
{string: navigator.userAgent, subString: "Opera", identity: "Opera"},
{string: navigator.userAgent, subString: "OPR", identity: "Opera"},
{string: navigator.userAgent, subString: "Chrome", identity: "Chrome"},
{string: navigator.userAgent, subString: "Safari", identity: "Safari"}
]
};
BrowserDetect.init();
var bv= BrowserDetect.browser;
if( bv == "Chrome"){
$("body").addClass("chrome");
}
else if(bv == "MS Edge"){
$("body").addClass("edge");
}
else if(bv == "Explorer"){
$("body").addClass("ie");
}
else if(bv == "Firefox"){
$("body").addClass("Firefox");
}
$(".relative").click(function(){
$(".oc").toggle('slide', { direction: 'left', mode: 'show' }, 500);
$(".oc1").css({
'width' : '100%',
'margin-left' : '0px',
});
});
To check for IE browser using following code.
console.log(/MSIE|Trident/.test(window.navigator.userAgent))
OR
var isIE = !!document.documentMode;
console.log(isIE)
Thanks
This combines both Rob's original answer and Pilau's update for 2016
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;
Here you find out which browser is it running.
function isValidBrowser(navigator){
var isChrome = navigator.indexOf('chrome'),
isFireFox= navigator.indexOf('firefox'),
isIE = navigator.indexOf('trident') ,
isValidChromeVer = parseInt(navigator.substring(isChrome+7, isChrome+8)) >= 4,
isValidFireForVer = parseInt(navigator.substring(isFireFox+8, isFireFox+9)) >= 3,
isValidIEVer = parseInt(navigator.substring(isIE+8, isIE+9)) >= 7;
if((isChrome > -1 && isValidChromeVer){ console.log("Chrome Browser")}
if(isFireFox > -1 && isValidFireForVer){ console.log("FireFox Browser")}
if(isIE > -1 && isValidIEVer)){ console.log("IE Browser")}
}
We can use below util methods
utils.isIE = function () {
var ver = navigator.userAgent;
return ver.indexOf("MSIE") !== -1 || ver.indexOf("Trident") !== -1; // need to check for Trident for IE11
};
utils.isIE32 = function () {
return (utils.isIE() && navigator.appVersion.indexOf('Win64') === -1);
};
utils.isChrome = function () {
return (window.chrome);
};
utils.isFF64 = function () {
var agent = navigator.userAgent;
return (agent.indexOf('Win64') >= 0 && agent.indexOf('Firefox') >= 0);
};
utils.isFirefox = function () {
return (navigator.userAgent.toLowerCase().indexOf('firefox') > -1);
};
const isChrome = /Chrome/.test(navigator.userAgent)
const isFirefox = /Firefox/.test(navigator.userAgent)
You can detect it like:
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) {
alert('Firefox');
}
import getAgent, { getAccurateAgent } from "#egjs/agent";
const agent = getAgent();
getAccurateAgent().then((accurate_agent)=>{
console.log(agent,'accurate.');
})
console.log(agent);
https://github.com/naver/egjs-agent
This method is currently valid for detecting all browsers. I quoted the vue-element-admin template
export function fnBrowserDetect() {
var browserName = (function(agent) {
switch (true) {
case agent.indexOf('edge') > -1: return 'MS Edge'
case agent.indexOf('edg/') > -1: return 'Edge (chromium based)'
case agent.indexOf('opr') > -1 && !!window.opr: return 'Opera'
case agent.indexOf('chrome') > -1 && !!window.chrome: return 'Chrome'
case agent.indexOf('trident') > -1: return 'MS IE'
case agent.indexOf('firefox') > -1: return 'Mozilla Firefox'
case agent.indexOf('safari') > -1: return 'Safari'
default: return 'other'
}
})(window.navigator.userAgent.toLowerCase())
return browserName.toLowerCase()
}
var BrowserType;
(function (BrowserType) {
BrowserType["OPERA"] = "Opera";
BrowserType["OPERA2"] = "OPR";
BrowserType["EDGE"] = "Edg";
BrowserType["CHROME"] = "Chrome";
BrowserType["SAFARI"] = "Safari";
BrowserType["FIREFOX"] = "Firefox";
BrowserType["UNKNOWN"] = "unknown";
})(BrowserType || (BrowserType = {}));
const detectBrowser = () => {
return Object.values(BrowserType).find((browser) => navigator.userAgent.indexOf(browser) != -1);
};
console.log(detectBrowser());
Simple:
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
if (navigator.appVersion.indexOf("Linux x86_64")!=-1) OSName="Ubuntu";
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;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
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 the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Hey! i see you\'re using '+browserName+'! <br>'
+'The full version of it is '+fullVersion+'. <br>'
+'Your major version is '+majorVersion+', <br>'
+'And your "navigator.appName" is '+navigator.appName+'. <br>'
+'Your "navigator.userAgent" is '+navigator.userAgent+'. <br>'
)
document.write('And, your OS is '+OSName+'. <br>');
Simple, single line of JavaScript code will give you the name of browser:
function GetBrowser()
{
return navigator ? navigator.userAgent.toLowerCase() : "other";
}

How to tell user to open page in Chrome with Browser Detect

I want to add a message that tells users to open the page in chrome if they're not in that browser. How can the below be adjusted to use document.write() instead of alert(), and also exclude writing the message if they're already in chrome? I found the below browser detect code here: https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator
var sBrowser, sUsrAg = navigator.userAgent;
if (sUsrAg.indexOf("Chrome") > -1) {
sBrowser = "Google Chrome";
} else if (sUsrAg.indexOf("Safari") > -1) {
sBrowser = "Apple Safari";
} else if (sUsrAg.indexOf("Opera") > -1) {
sBrowser = "Opera";
} else if (sUsrAg.indexOf("Firefox") > -1) {
sBrowser = "Mozilla Firefox";
} else if (sUsrAg.indexOf("MSIE") > -1) {
sBrowser = "Microsoft Internet Explorer";
}
alert("You are using: " + sBrowser);
A simple solution would be to not assign any value to sBrowser if the user is using chrome, and then check for undefined.
var sBrowser, sUsrAg = navigator.userAgent;
if (sUsrAg.indexOf("Safari") > -1) {
sBrowser = "Apple Safari";
} else if (sUsrAg.indexOf("Opera") > -1) {
sBrowser = "Opera";
} else if (sUsrAg.indexOf("Firefox") > -1) {
sBrowser = "Mozilla Firefox";
} else if (sUsrAg.indexOf("MSIE") > -1) {
sBrowser = "Microsoft Internet Explorer";
}
if (sBrowser != null) {
document.write("You are using " + sBrowser + ". Use Chrome instead"); // or whatever
}
A problem with this approach is that you have to account for every single browser in existence. Just check for chrome, and then tell everyone else to use it. You lose the ability to tell them what browser they're using but that seems unimportant here.
var sUsrAg = navigator.userAgent,
usingChrome = sUsrAg.indexOf("Chrome") > -1;
if (!usingChrome) {
document.write("You are not using Chrome. Switch to blah blah blah"); // or whatever
}

Trying to autoselect option box based on users OS

So I have a live website here: http://www.trock.net/#/downloads
What I am trying to do is preselect the "select operating system" option based on the users OS.
The apps.js is located here:
http://www.trock.net/js/app.js.
The raw HTML for the download page is located here: www.trock.net/includes/downloads.html
Now, the issue is that the detectOS function I have does not seem to work. I have tried attaching it to ng-init on the app and ng-init on a div after the select box but that does not work. If I attach ng-click and click it, it works as expected.
Each option has an ID which is what I am using to find the element so I can set 'selected' to true. Is there a better way of doing this using angular?
How would I go about making this work, is the issue that I am calling the function too early or perhaps too late?
Code of interest in apps.js:
//Auto select Operating System based on detection
$scope.detectOS = function() {
var processorArchitecture = "";
var userOS = "";
if (navigator.userAgent.indexOf("WOW64") != -1 ||
navigator.userAgent.indexOf("Win64") != -1 ){
processorArchitecture = "64";
} else { //Assume 32 bit
processorArchitecture = "32";
}
//Detect the OS
if (navigator.platform.indexOf("Win") != -1){
userOS = "win";
if (processorArchitecture == "64")
processorArchitecture = "32";
}
else if (navigator.platform.indexOf("Mac") != -1){
userOS = "mac";
if (processorArchitecture == "64")
processorArchitecture = "32";
}
else if (navigator.platform.indexOf("Lin") != -1){
userOS = "lin";
}
//Check for valid detection
if (userOS != "" && processorArchitecture != "") {
//Valid match found
var optionSelectionID = userOS + processorArchitecture;
//Auto detect OS
//We will find only 1 instance of said query
angular.element( document.querySelector( "#win32") )[0].selected = true;
}
};
I also made a plunker which actually works so it must be something else I am doing on the website (perhaps loading in other .html pages ajax style).
Link: http://plnkr.co/edit/zlmk24aVHeBNz79PjypP?p=preview
Okay so I solved the issue, it seems that the presence of the ng-model was stopping the above code from working. Removing it means it worked fine but I needed the ng-model set to do other things.
Anyway, I ended up using the ng-options derivative like so to solve my problem:
<select ng-model="operatingSystemID" ng-options="os as os.label for os in osList track by os.id" id="download-dropdown">
I used this as my osList:
//Create supported operating systems list
$scope.osList = [
{
id: "win32",
label: "Windows (32/64 bit)"
},
{
id: "mac32",
label: "Mac OS (32/64 bit)"
},
{
id: "lin32",
label: "Linux (32 bit)"
},
{
id: "lin64",
label: "Linux (64 bit)"
}
];
And this was my new detectOS function:
$scope.detectOS = function() {
var processorArchitecture = "";
var processorArchitectureCompat = "";
var userOS = "";
var userOSNicename = "";
if (navigator.userAgent.indexOf("WOW64") != -1 ||
navigator.userAgent.indexOf("Win64") != -1 ){
processorArchitecture = "64";
} else { //Assume 32 bit
processorArchitecture = "32";
}
processorArchitectureCompat = processorArchitecture;
//Detect the OS
if (navigator.platform.indexOf("Win") != -1){
userOS = "win";
userOSNicename = "Windows";
if (processorArchitecture == "64")
processorArchitectureCompat = "32";
}
else if (navigator.platform.indexOf("Mac") != -1){
userOS = "mac";
userOSNicename = "Mac OS";
if (processorArchitecture == "64")
processorArchitectureCompat = "32";
}
else if (navigator.platform.indexOf("Lin") != -1){
userOS = "lin";
userOSNicename = "Linux";
}
//Check for valid detection
if (userOS != "" && processorArchitecture != "") {
//Valid match found
var optionSelectionID = userOS + processorArchitectureCompat;
//Output detected option to os message section
$scope.os_detection_box = $sce.trustAsHtml("(We have detected your OS as " + userOSNicename + " " +processorArchitecture + " bits)");
//Auto select the detected option
$scope.operatingSystemID = {id: optionSelectionID};
}
};

How to alert a user their browser is not the latest version?

I found a .NET version of this, but can't find a javascript/jquery way to do this. I test my site in the latest IE/Chrome/FF/Safari/Opera. That is a difficult enough task (to me) without adding backward compatibility. The message will be to simply use another browser which is up to date. Are there any scripts that do this? I'm hoping to find a resource that tracks this sort of thing so I don't have to.
You could navigator.appVersion to find the versions and filter the relevant version using navigator.appName which can give you a version number you can compare against a minimum required version that you could set.
Using somthing like this (JSFiddel) you could break down the string and get the version.
var objappVersion = navigator.appVersion;
var objAgent = navigator.userAgent;
var objbrowserName = navigator.appName;
var objfullVersion = '' + parseFloat(navigator.appVersion);
var objBrMajorVersion = parseInt(navigator.appVersion, 10);
var objOffsetName, objOffsetVersion, ix;
if ((objOffsetVersion = objAgent.indexOf("Chrome")) != -1) {
objbrowserName = "Chrome";
objfullVersion = objAgent.substring(objOffsetVersion + 7);
}
else if ((objOffsetVersion = objAgent.indexOf("MSIE")) != -1) {
objbrowserName = "Microsoft Internet Explorer";
objfullVersion = objAgent.substring(objOffsetVersion + 5);
} // In Firefox
else if ((objOffsetVersion = objAgent.indexOf("Firefox")) != -1) {
objbrowserName = "Firefox";
}
else if ((objOffsetVersion = objAgent.indexOf("Safari")) != -1) {
objbrowserName = "Safari";
objfullVersion = objAgent.substring(objOffsetVersion + 7);
if ((objOffsetVersion = objAgent.indexOf("Version")) != -1) objfullVersion = objAgent.substring(objOffsetVersion + 8);
} // For other browser "name/version" is at the end of userAgent
else if ((objOffsetName = objAgent.lastIndexOf(' ') + 1) < (objOffsetVersion = objAgent.lastIndexOf('/'))) {
objbrowserName = objAgent.substring(objOffsetName, objOffsetVersion);
objfullVersion = objAgent.substring(objOffsetVersion + 1);
if (objbrowserName.toLowerCase() == objbrowserName.toUpperCase()) {
objbrowserName = navigator.appName;
}
}
if ((ix = objfullVersion.indexOf(";")) != -1) objfullVersion = objfullVersion.substring(0, ix);
if ((ix = objfullVersion.indexOf(" ")) != -1) objfullVersion = objfullVersion.substring(0, ix);
objBrMajorVersion = parseInt('' + objfullVersion, 10);
if (isNaN(objBrMajorVersion)) {
objfullVersion = '' + parseFloat(navigator.appVersion);
objBrMajorVersion = parseInt(navigator.appVersion, 10);
}
Example code from here.
However it would probably be more beneficial to check for compatibility using the individual features that may lack support and inform the user of any incompatibility's and explain any ramifications.
Check what these guys did: Browser Update Initiative. You can integrate it easily and they offer code samples: http://browser-update.org/
It is going to be much harder to implement on your own and you will have to regularly update your browser version data.
One solution is to have a warning message in a div, and this div is hidden in a subsequent media query section. Only browsers supporting CSS 3 media queries will then auto hide this warning message div.

How can I detect browser type using jQuery?

I want to detect if the user is using IE and Firefox but I cannot find the script.
I have code as below:
$(document).ready(function(e) {
$.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
if($.browser.chrome){
alert(1);
//this work well
}
else if(//the browser is IE){alert(2);}
else if(//the browser is Firefox){alert(3);}
//The problem is that I don't know how to write a script for IE and FireFox browser for chrome is work fine
)};
The best solution is probably: use Modernizr.
However, if you necessarily want to use $.browser property, you can do it using jQuery Migrate plugin (for JQuery >= 1.9 - in earlier versions you can just use it) and then do something like:
if($.browser.chrome) {
alert(1);
} else if ($.browser.mozilla) {
alert(2);
} else if ($.browser.msie) {
alert(3);
}
And if you need for some reason to use navigator.userAgent, then it would be:
$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase());
My solution for ie detection:
if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i) ){
$("html").addClass("ie");
}
Jquery needed.
You can use this code to find correct browser and you can make changes for any target browser.....
function myFunction() {
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){
alert('Opera');
}
else if(navigator.userAgent.indexOf("Chrome") != -1 ){
alert('Chrome');
}
else if(navigator.userAgent.indexOf("Safari") != -1){
alert('Safari');
}
else if(navigator.userAgent.indexOf("Firefox") != -1 ){
alert('Firefox');
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){
alert('IE');
}
else{
alert('unknown');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Browser detector</title>
</head>
<body onload="myFunction()">
// your code here
</body>
</html>
You shouldn't write your own browser-detection code - it's been done many times before. Use Modernizr to detect independent browser features instead. It's better to detect the various features than to detect entire browsers because various browsers may support different set of features and those features may even change through various versions of the same browser. If you detect the presence of a given feature, your code will likely work better in more browsers. This is especially true for the various mobile browsers.
When you run Modernizr, it'll update your HEAD element's class attribute so that it lists the various features of the browser that you're using - you can then use Javascript to query the attribute and decide what to do if a feature is present (or missing).
Use this:
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], function ($) {
return factory($);
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
// Node-like environment
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function(jQuery) {
"use strict";
function uaMatch( ua ) {
// If an UA is not provided, default to the current browser UA.
if ( ua === undefined ) {
ua = window.navigator.userAgent;
}
ua = ua.toLowerCase();
var match = /(edge)\/([\w.]+)/.exec( ua ) ||
/(opr)[\/]([\w.]+)/.exec( ua ) ||
/(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
var platform_match = /(ipad)/.exec( ua ) ||
/(ipod)/.exec( ua ) ||
/(iphone)/.exec( ua ) ||
/(kindle)/.exec( ua ) ||
/(silk)/.exec( ua ) ||
/(android)/.exec( ua ) ||
/(windows phone)/.exec( ua ) ||
/(win)/.exec( ua ) ||
/(mac)/.exec( ua ) ||
/(linux)/.exec( ua ) ||
/(cros)/.exec( ua ) ||
/(playbook)/.exec( ua ) ||
/(bb)/.exec( ua ) ||
/(blackberry)/.exec( ua ) ||
[];
var browser = {},
matched = {
browser: match[ 5 ] || match[ 3 ] || match[ 1 ] || "",
version: match[ 2 ] || match[ 4 ] || "0",
versionNumber: match[ 4 ] || match[ 2 ] || "0",
platform: platform_match[ 0 ] || ""
};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
browser.versionNumber = parseInt(matched.versionNumber, 10);
}
if ( matched.platform ) {
browser[ matched.platform ] = true;
}
// These are all considered mobile platforms, meaning they run a mobile browser
if ( browser.android || browser.bb || browser.blackberry || browser.ipad || browser.iphone ||
browser.ipod || browser.kindle || browser.playbook || browser.silk || browser[ "windows phone" ]) {
browser.mobile = true;
}
// These are all considered desktop platforms, meaning they run a desktop browser
if ( browser.cros || browser.mac || browser.linux || browser.win ) {
browser.desktop = true;
}
// Chrome, Opera 15+ and Safari are webkit based browsers
if ( browser.chrome || browser.opr || browser.safari ) {
browser.webkit = true;
}
// IE11 has a new token so we will assign it msie to avoid breaking changes
// IE12 disguises itself as Chrome, but adds a new Edge token.
if ( browser.rv || browser.edge ) {
var ie = "msie";
matched.browser = ie;
browser[ie] = true;
}
// Blackberry browsers are marked as Safari on BlackBerry
if ( browser.safari && browser.blackberry ) {
var blackberry = "blackberry";
matched.browser = blackberry;
browser[blackberry] = true;
}
// Playbook browsers are marked as Safari on Playbook
if ( browser.safari && browser.playbook ) {
var playbook = "playbook";
matched.browser = playbook;
browser[playbook] = true;
}
// BB10 is a newer OS version of BlackBerry
if ( browser.bb ) {
var bb = "blackberry";
matched.browser = bb;
browser[bb] = true;
}
// Opera 15+ are identified as opr
if ( browser.opr ) {
var opera = "opera";
matched.browser = opera;
browser[opera] = true;
}
// Stock Android browsers are marked as Safari on Android.
if ( browser.safari && browser.android ) {
var android = "android";
matched.browser = android;
browser[android] = true;
}
// Kindle browsers are marked as Safari on Kindle
if ( browser.safari && browser.kindle ) {
var kindle = "kindle";
matched.browser = kindle;
browser[kindle] = true;
}
// Kindle Silk browsers are marked as Safari on Kindle
if ( browser.safari && browser.silk ) {
var silk = "silk";
matched.browser = silk;
browser[silk] = true;
}
// Assign the name and platform variable
browser.name = matched.browser;
browser.platform = matched.platform;
return browser;
}
// Run the matching process, also assign the function to the returned object
// for manual, jQuery-free use if desired
window.jQBrowser = uaMatch( window.navigator.userAgent );
window.jQBrowser.uaMatch = uaMatch;
// Only assign to jQuery.browser if jQuery is loaded
if ( jQuery ) {
jQuery.browser = window.jQBrowser;
}
return window.jQBrowser;
}));
Try to use it
$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});
$.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
if($.browser.chrome){
alert(1);
}
UPDATE:(10x to #Mr. Bacciagalupe)
jQuery has removed $.browser from 1.9 and their latest release.
But you can still use $.browser as a standalone plugin, found here
Another way to find versions of IE
http://tanalin.com/en/articles/ie-version-js/
IE versions Condition to check for
IE 10 or older - document.all <BR/>
IE 9 or older - document.all && !window.atob <br/>
IE 8 or older - document.all && !document.addEventListener <br/>
IE 7 or older - document.all && !document.querySelector <br/>
IE 6 or older - document.all && !window.XMLHttpRequest <br/>
IE 5.x - document.all && !document.compatMode
You can get Browser type here:
<script>
var browser_type = Object.keys($.browser)[0];
alert(browser_type);
</script>
$(document).ready(function(){
alert('sdfsd');
checkOperatingSystem();
});
function checkOperatingSystem(){
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android/i.test(userAgent)) {
alert('android');
}
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
alert('ios');
}
if (navigator.appVersion.indexOf("Win")!=-1)
{
}
if (navigator.appVersion.indexOf("Mac")!=-1)
{
}
}
I have used this and it works for me.Also include jquery migrate plugin,and jquery file.
if ( $.browser.webkit ) {
alert( "This is WebKit!" );
}

Categories