event-tracking.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. if (typeof window.gtag !== 'function') return
  26. if (['paywall-click', 'paywall-prompt', 'plans-page-click'].includes(key)) {
  27. window.gtag('event', key, segmentation)
  28. }
  29. }
  30. export function sendMBOnce(key, segmentation = {}) {
  31. if (alreadySent(key)) return
  32. sendMB(key, segmentation)
  33. markAsSent(key)
  34. }
  35. export function sendMBSampled(key, body = {}, rate = 0.01) {
  36. if (Math.random() < rate) {
  37. sendMB(key, body)
  38. }
  39. }
  40. function sendBeacon(key, data) {
  41. if (!navigator || !navigator.sendBeacon) return
  42. data._csrf = window.csrfToken
  43. const blob = new Blob([JSON.stringify(data)], {
  44. type: 'application/json; charset=UTF-8',
  45. })
  46. try {
  47. navigator.sendBeacon(`/event/${key}`, blob)
  48. } catch (error) {
  49. // Ignored. There's a range of browser for which `navigator.sendBeacon` is available but
  50. // will throw an error if it's called with an unacceptable mime-typed Blob as the data.
  51. }
  52. }