2021-04-30 16:20:16 -04:00
|
|
|
import { postJSON } from './fetch-json'
|
2021-06-10 04:04:21 -04:00
|
|
|
import sessionStorage from '../infrastructure/session-storage'
|
|
|
|
|
|
|
|
const CACHE_KEY = 'mbEvents'
|
2021-04-30 16:20:16 -04:00
|
|
|
|
|
|
|
export function send(category, action, label, value) {
|
|
|
|
if (typeof window.ga === 'function') {
|
|
|
|
window.ga('send', 'event', category, action, label, value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-10 04:04:21 -04:00
|
|
|
export function sendMB(key, segmentation = {}) {
|
|
|
|
postJSON(`/event/${key}`, { body: segmentation, keepalive: true }).catch(
|
|
|
|
() => {
|
|
|
|
// ignore errors
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function sendMBOnce(key, segmentation = {}) {
|
|
|
|
let eventCache = sessionStorage.getItem(CACHE_KEY)
|
|
|
|
|
|
|
|
// Initialize as an empy object if the event cache is still empty.
|
|
|
|
if (eventCache == null) {
|
|
|
|
eventCache = {}
|
|
|
|
sessionStorage.setItem(CACHE_KEY, eventCache)
|
|
|
|
}
|
|
|
|
|
|
|
|
const isEventInCache = eventCache[key] || false
|
|
|
|
if (!isEventInCache) {
|
|
|
|
eventCache[key] = true
|
|
|
|
sessionStorage.setItem(CACHE_KEY, eventCache)
|
|
|
|
sendMB(key, segmentation)
|
|
|
|
}
|
2021-04-30 16:20:16 -04:00
|
|
|
}
|
2021-05-21 07:32:07 -04:00
|
|
|
|
|
|
|
export function sendMBSampled(key, body = {}, rate = 0.01) {
|
|
|
|
if (Math.random() < rate) {
|
|
|
|
sendMB(key, body)
|
|
|
|
}
|
|
|
|
}
|