event-tracking.js 1.2 KB

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