My browser detection code is something like this
navigator.sayswho = (function () {
var ua = navigator.userAgent;
var tem;
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE ' + (tem[1] || '');
}
if (M[1] === 'Chrome') {
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
alert(navigator.sayswho); // outputs: `Chrome 62`
});
All looks good but on edge this code returns browser as "Chrome". How can I fix this?
Usually I put Edge check on top to pass this. When you try to see
userAgent in chrome: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
userAgent in Edge: Mozilla/5.0 (Windows NT 10.0; Win64; x64; ServiceUI 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19041
Even in Edge it contains chrome before the Edge. Used below code to check this normally check for Edge before chrome.
function fnBrowserDetect(){
let userAgent = navigator.userAgent;
let browserName;
if(userAgent.match(/edg/i)){
browserName = "edge";
}
else if(userAgent.match(/chrome|chromium|crios/i)){
browserName = "chrome";
}else if(userAgent.match(/firefox|fxios/i)){
browserName = "firefox";
} else if(userAgent.match(/safari/i)){
browserName = "safari";
}else if(userAgent.match(/opr\//i)){
browserName = "opera";
}else{
browserName="No browser detection";
}
return "You are using "+ browserName +" browser";
}
Basically you're currently using the legacy method to detect the user client. New Standard recommend to use the navigator.userAgentData.brands to detect the actual browser client name either it's chrome or edge.
You can see it here for edge.
You can also check out the official docs of mdn for this purpose.