hotjar.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import getMeta from '@/utils/meta'
  2. import { debugConsole } from '@/utils/debugging'
  3. import { initializeHotjar } from '@/infrastructure/hotjar-snippet'
  4. const { hotjarId, hotjarVersion } = getMeta('ol-ExposedSettings')
  5. const shouldLoadHotjar = getMeta('ol-shouldLoadHotjar')
  6. let hotjarInitialized = false
  7. if (hotjarId && hotjarVersion && shouldLoadHotjar) {
  8. const loadHotjar = () => {
  9. // consent needed
  10. if (!document.cookie.split('; ').some(item => item === 'oa=1')) {
  11. return
  12. }
  13. if (!/^\d+$/.test(hotjarId) || !/^\d+$/.test(hotjarVersion)) {
  14. debugConsole.error('Invalid Hotjar id or version')
  15. return
  16. }
  17. // avoid inserting twice
  18. if (!hotjarInitialized) {
  19. debugConsole.log('Loading Hotjar')
  20. hotjarInitialized = true
  21. initializeHotjar(hotjarId, hotjarVersion)
  22. }
  23. }
  24. // load when idle, if supported
  25. if (typeof window.requestIdleCallback === 'function') {
  26. window.requestIdleCallback(loadHotjar)
  27. } else {
  28. loadHotjar()
  29. }
  30. // listen for consent
  31. window.addEventListener('cookie-consent', event => {
  32. if ((event as CustomEvent<boolean>).detail) {
  33. loadHotjar()
  34. }
  35. })
  36. }