The navigator is an object that has some information about the browser. One property is navigator.userAgent, which is a long string of browser identification.
window.navigator.userAgent
//Firefox | "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 |
//IE | Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30) |
//Chrome | Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 |
Because the browsers have different capabilities, developers can use userAgent
string to identify the browser and provide different versions of the code.
Example to identify different browsers.
if (navigator.userAgent.indexOf("Chrome") > -1) { sBrowser = "Google Chrome"; } else if (navigator.userAgent.indexOf("Safari") > -1) { sBrowser = "Apple Safari"; } else if (navigator.userAgent.indexOf("Opera") > -1) { sBrowser = "Opera"; } else if (navigator.userAgent.indexOf("Firefox") > -1) { sBrowser = "Mozilla Firefox"; } else if (navigator.userAgent.indexOf("MSIE") > -1) { sBrowser = "Microsoft Internet Explorer"; } console.log("You are using: " + sBrowser);
It is better not to rely on the user agent string as it's hard to keep track of all browsers and their different versions. It's much easier to simply check if the feature you intend to use is indeed available in the user's browser.
if (typeof window.addEventListener === 'function') { // feature is supported, let's use it } else { // this feature is not supported, go another way }
Property | Description |
---|---|
appCodeName | Returns the code name of the browser |
appName | Returns the name of the browser |
appVersion | Returns the version information of the browser |
cookieEnabled | Determines whether cookies are enabled in the browser |
geolocation | Returns a Geolocation object that can be used to locate the user's position |
language | Returns the language of the browser |
onLine | Determines whether the browser is online |
platform | Returns for which platform the browser is compiled |
product | Returns the engine name of the browser |
userAgent | Returns the user-agent header sent by the browser to the server |
Method | Description |
---|---|
javaEnabled() | Specifies whether or not the browser has Java enabled |
taintEnabled() | Removed in JavaScript version 1.2. Specifies whether the browser has data tainting enabled |