browser.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import UAParser from 'ua-parser-js'
  3. const parser = new UAParser()
  4. export const browser = parser.getBrowser()
  5. export const device = parser.getDevice()
  6. export const os = parser.getOS()
  7. export const generateFingerprint = () => {
  8. const windowResolution = `${window.screen.availWidth}x${window.screen.availHeight}/${window.screen.pixelDepth}`
  9. const timezone = new Date().toString().match(/\s\(.+?\)$/)?.[0]
  10. const getMajorVersion = (version?: string): string => {
  11. if (!version) return 'unknown'
  12. const versionParts = version.split('.')
  13. return versionParts[0]
  14. }
  15. const hashCode = (string: string) => {
  16. return string.split('').reduce((a, b) => {
  17. // eslint-disable-next-line no-bitwise
  18. a = (a << 5) - a + b.charCodeAt(0)
  19. // eslint-disable-next-line no-bitwise
  20. return a & a
  21. }, 0)
  22. }
  23. return hashCode(
  24. `${browser.name}${getMajorVersion(browser.version)}${
  25. os.name
  26. }${getMajorVersion(os.version)}${windowResolution}${timezone}`,
  27. ).toString()
  28. }
  29. export const setCursorAtTextEnd = (element: HTMLElement) => {
  30. const range = document.createRange()
  31. const selection = window.getSelection()
  32. range.selectNodeContents(element)
  33. range.collapse(false)
  34. if (!selection) return
  35. selection.removeAllRanges()
  36. selection.addRange(range)
  37. }
  38. export const setPastedTextToCurrentSelection = (
  39. event: ClipboardEvent,
  40. options = { format: 'text/plain' },
  41. ) => {
  42. const text = event.clipboardData?.getData(options.format)
  43. const selection = window.getSelection()
  44. if (!selection?.rangeCount || !text?.length) return false
  45. selection.deleteFromDocument()
  46. selection.getRangeAt(0).insertNode(document.createTextNode(text))
  47. selection.collapseToEnd()
  48. }