getUserAgent.mjs

  1. import { UAParser } from 'ua-parser-js'
  2. import get from 'lodash-es/get.js'
  3. import isstr from './isstr.mjs'
  4. import getGlobal from './getGlobal.mjs'
  5. function getUAParser() {
  6. let g = getGlobal()
  7. let x = UAParser || g.UAParser
  8. return x
  9. }
  10. /**
  11. * 取得使用者瀏覽器資訊,後端nodejs環境使用需提供user agent字串
  12. *
  13. * Unit Test: {@link https://github.com/yuda-lyu/wsemi/blob/master/test/getUserAgent.test.mjs Github}
  14. * @memberOf wsemi
  15. * @param {String} [v=null] 輸入user agent字串,預設null
  16. * @returns {Object} 回傳使用者瀏覽器資訊物件
  17. * @example
  18. *
  19. * let ua = 'Mozilla/5.0 (compatible; Konqueror/4.1; OpenBSD) KHTML/4.1.4 (like Gecko)'
  20. * console.log(getUserAgent(ua))
  21. * // => {
  22. * browsername: 'Konqueror',
  23. * browserversion: '4.1',
  24. * cpuarchitecture: '',
  25. * devicetype: '',
  26. * engineinfor: 'KHTML4.1.4',
  27. * platform: 'OpenBSDundefined'
  28. * }
  29. *
  30. */
  31. function getUserAgent(v = null) {
  32. //parser
  33. let parser
  34. let Upr = getUAParser()
  35. if (isstr(v)) {
  36. parser = new Upr(v)
  37. }
  38. else {
  39. parser = new Upr()
  40. }
  41. let oua = parser.getResult()
  42. return {
  43. browsername: oua.browser.name,
  44. browserversion: oua.browser.version,
  45. engineinfor: oua.engine.name + oua.engine.version,
  46. platform: oua.os.name + oua.os.version,
  47. devicetype: get(oua.device, 'type', ''),
  48. cpuarchitecture: get(oua.cpu, 'architecture', '')
  49. }
  50. }
  51. export default getUserAgent