event-tracking.js 2.0 KB

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