event-tracking.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { postJSON } from './fetch-json'
  2. import sessionStorage from '../infrastructure/session-storage'
  3. const CACHE_KEY = 'mbEvents'
  4. export function send(category, action, label, value) {
  5. if (typeof window.ga === 'function') {
  6. window.ga('send', 'event', category, action, label, value)
  7. }
  8. }
  9. export function sendMB(key, segmentation = {}) {
  10. postJSON(`/event/${key}`, { body: segmentation, keepalive: true }).catch(
  11. () => {
  12. // ignore errors
  13. }
  14. )
  15. }
  16. export function sendMBOnce(key, segmentation = {}) {
  17. let eventCache = sessionStorage.getItem(CACHE_KEY)
  18. // Initialize as an empy object if the event cache is still empty.
  19. if (eventCache == null) {
  20. eventCache = {}
  21. sessionStorage.setItem(CACHE_KEY, eventCache)
  22. }
  23. const isEventInCache = eventCache[key] || false
  24. if (!isEventInCache) {
  25. eventCache[key] = true
  26. sessionStorage.setItem(CACHE_KEY, eventCache)
  27. sendMB(key, segmentation)
  28. }
  29. }
  30. export function sendMBSampled(key, body = {}, rate = 0.01) {
  31. if (Math.random() < rate) {
  32. sendMB(key, body)
  33. }
  34. }