In some cases, you may need to detect the browser that the user is using. This can be useful for example to show a message to the user to update their browser if it is not supported.
navigator.userAgent
is a property that returns the user agent string for the current browser. This string can be used to detect the browser and its version.
Following code will detect the browser and display the name of the browser.
function getBrowserType() {
if (navigator.userAgent.indexOf("MSIE 7") > -1) {
return BrowserString("MSIE 7");
}
if (navigator.userAgent.indexOf("MSIE 8") > -1) {
return BrowserString("MSIE 8");
}
if (navigator.userAgent.indexOf("MSIE 9") > -1) {
return BrowserString("MSIE 9");
}
if (navigator.userAgent.indexOf("MSIE 10") > -1) {
return BrowserString("MSIE 10");
}
if (navigator.userAgent.indexOf("rv:11.0") > -1) {
return BrowserString("rv:11.0");
}
if (navigator.userAgent.indexOf("Firefox") > -1) {
return BrowserString("Firefox");
}
if (navigator.userAgent.indexOf("Chrome") > -1) {
return BrowserString("Chrome");
}
if (navigator.userAgent.indexOf("Opera") > -1) {
return BrowserString("Opera");
} else {
return "Unknown";
}
}
Here are the properties of navigator.userAgent
Property | Description |
---|---|
navigator.userAgent | Returns the user agent string for the current browser. |
navigator.appName | Returns the name of the browser. |
navigator.appVersion | Returns the version information of the browser. |
navigator.platform | Returns for which platform the browser is compiled. |
navigator.cookieEnabled | Returns whether cookies are enabled in the browser. |
navigator.javaEnabled() | Returns whether Java is enabled in the browser. |
navigator.onLine | Returns whether the browser is online. |
navigator.language | Returns the language of the browser. |
navigator.userLanguage | Returns the language of the browser. |
navigator.systemLanguage | Returns the operating system language. |
navigator.product | Returns the engine name of the browser. |
navigator.productSub | Returns the engine version of the browser. |
navigator.vendor | Returns the vendor name of the browser. |
navigator.vendorSub | Returns the vendor version of the browser. |
navigator.appCodeName | Returns the code name of the browser. |
navigator.appMinorVersion | Returns the minor version information of the browser. |
navigator.mimeTypes | Returns an array of all the MIME types supported by the browser. |
Why not to use JS browser detection?
JS browser detection is not a good practice. It is better to use feature detection instead of browser detection. Its better because it is more reliable and it is more future proof. AlsoJS based browser detection can be spoofed by the user.