event-tracking.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import sessionStorage from '../infrastructure/session-storage'
  2. const CACHE_KEY = 'mbEvents'
  3. function alreadySent(key) {
  4. const eventCache = sessionStorage.getItem(CACHE_KEY) || {}
  5. return !!eventCache[key]
  6. }
  7. function markAsSent(key) {
  8. const eventCache = sessionStorage.getItem(CACHE_KEY) || {}
  9. eventCache[key] = true
  10. sessionStorage.setItem(CACHE_KEY, eventCache)
  11. }
  12. export function send(category, action, label, value) {
  13. if (typeof window.ga === 'function') {
  14. window.ga('send', 'event', category, action, label, value)
  15. }
  16. }
  17. export function sendOnce(category, action, label, value) {
  18. if (alreadySent(category)) return
  19. if (typeof window.ga !== 'function') return
  20. window.ga('send', 'event', category, action, label, value)
  21. markAsSent(category)
  22. }
  23. export function sendMB(key, segmentation = {}) {
  24. sendBeacon(key, segmentation)
  25. }
  26. export function sendMBOnce(key, segmentation = {}) {
  27. if (alreadySent(key)) return
  28. sendMB(key, segmentation)
  29. markAsSent(key)
  30. }
  31. export function sendMBSampled(key, body = {}, rate = 0.01) {
  32. if (Math.random() < rate) {
  33. sendMB(key, body)
  34. }
  35. }
  36. function sendBeacon(key, data) {
  37. if (!navigator || !navigator.sendBeacon) return
  38. data._csrf = window.csrfToken
  39. const blob = new Blob([JSON.stringify(data)], {
  40. type: 'application/json; charset=UTF-8',
  41. })
  42. navigator.sendBeacon(`/event/${key}`, blob)
  43. }