Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser detection in JavaScript? [duplicate]

How do I determine the exact browser and version using JavaScript?

like image 702
Probocop Avatar asked Mar 08 '10 11:03

Probocop


1 Answers

navigator.saysWho = (() => {   const { userAgent } = navigator   let match = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []   let temp    if (/trident/i.test(match[1])) {     temp = /\brv[ :]+(\d+)/g.exec(userAgent) || []      return `IE ${temp[1] || ''}`   }    if (match[1] === 'Chrome') {     temp = userAgent.match(/\b(OPR|Edge)\/(\d+)/)      if (temp !== null) {       return temp.slice(1).join(' ').replace('OPR', 'Opera')     }      temp = userAgent.match(/\b(Edg)\/(\d+)/)      if (temp !== null) {       return temp.slice(1).join(' ').replace('Edg', 'Edge (Chromium)')     }   }    match = match[2] ? [ match[1], match[2] ] : [ navigator.appName, navigator.appVersion, '-?' ]   temp = userAgent.match(/version\/(\d+)/i)    if (temp !== null) {     match.splice(1, 1, temp[1])   }    return match.join(' ') })()  console.log(navigator.saysWho) // outputs: `Chrome 89`

As the name implies, this will tell you the name and version number supplied by the browser.

It is handy for sorting test and error results, when you are testing new code on multiple browsers.

like image 104
kennebec Avatar answered Sep 29 '22 03:09

kennebec