It is sometimes required to detect the user's browser and run a different script, load a new page etc. Browser detection can be done by checking the browser's
userAgent string. But this method is not very reliable, because
userAgent strings keep on changing and some browser manufacturers deliberately make them confusing to avoid detection. For example, Internet Explorer used to have "MSIE" in the userAgent string, but it was dropped in IE11.
The most reliable and accurate method is feature-based detection ie., check the browser capabilities, features that are unique to a browser.
There are several different strategies for implementing feature based browser detection. The basic idea is to check for an object or property that is unique to a browser and promptly separating it from other browser. Here is an example for browser sniffing some of the most popular browsers:
For IE detection, the document.documentMode property can be used. For Internet Explorer it is an integer related to version and it will be
For Chrome you can check two objects, window.chrome and window.chrome.webstore
For Firefox detection, the InstallTrigger API can be checked. This is Firefox's API to install add-ons and undefined for other browsers.
Opera tries to closely resemble Chrome, but you can use window.opr and opr.addons for Opera 20+. For previous versions, window.opera and userAgent sniffing can be used.
Edge can be detected by StyleMedia constructor
Safari can be detected by the naming pattern of its constructors.
Below is a sample code that implements the strategy described