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
|
|
|
|
2021-09-16 11:18:16 -04:00
|
|
|
function alreadySent(key) {
|
|
|
|
const eventCache = sessionStorage.getItem(CACHE_KEY) || {}
|
|
|
|
return !!eventCache[key]
|
|
|
|
}
|
|
|
|
function markAsSent(key) {
|
|
|
|
const eventCache = sessionStorage.getItem(CACHE_KEY) || {}
|
|
|
|
eventCache[key] = true
|
|
|
|
sessionStorage.setItem(CACHE_KEY, eventCache)
|
|
|
|
}
|
|
|
|
|
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-09-16 11:18:16 -04:00
|
|
|
export function sendOnce(category, action, label, value) {
|
|
|
|
if (alreadySent(category)) return
|
|
|
|
if (typeof window.ga !== 'function') return
|
|
|
|
|
|
|
|
window.ga('send', 'event', category, action, label, value)
|
|
|
|
markAsSent(category)
|
|
|
|
}
|
|
|
|
|
2021-06-10 04:04:21 -04:00
|
|
|
export function sendMB(key, segmentation = {}) {
|
2023-01-09 11:21:06 -05:00
|
|
|
if (!segmentation.page) {
|
|
|
|
segmentation.page = window.location.pathname
|
|
|
|
}
|
|
|
|
|
2021-08-11 04:50:38 -04:00
|
|
|
sendBeacon(key, segmentation)
|
2022-02-03 07:49:05 -05:00
|
|
|
|
|
|
|
if (typeof window.gtag !== 'function') return
|
|
|
|
if (['paywall-click', 'paywall-prompt', 'plans-page-click'].includes(key)) {
|
|
|
|
window.gtag('event', key, segmentation)
|
|
|
|
}
|
2021-06-10 04:04:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export function sendMBOnce(key, segmentation = {}) {
|
2021-09-16 11:18:16 -04:00
|
|
|
if (alreadySent(key)) return
|
|
|
|
sendMB(key, segmentation)
|
2021-10-15 05:46:23 -04:00
|
|
|
markAsSent(key)
|
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)
|
|
|
|
}
|
|
|
|
}
|
2021-08-11 04:50:38 -04:00
|
|
|
|
|
|
|
function sendBeacon(key, data) {
|
|
|
|
if (!navigator || !navigator.sendBeacon) return
|
|
|
|
|
|
|
|
data._csrf = window.csrfToken
|
|
|
|
const blob = new Blob([JSON.stringify(data)], {
|
|
|
|
type: 'application/json; charset=UTF-8',
|
|
|
|
})
|
2021-11-29 06:59:18 -05:00
|
|
|
try {
|
|
|
|
navigator.sendBeacon(`/event/${key}`, blob)
|
|
|
|
} catch (error) {
|
|
|
|
// Ignored. There's a range of browser for which `navigator.sendBeacon` is available but
|
|
|
|
// will throw an error if it's called with an unacceptable mime-typed Blob as the data.
|
|
|
|
}
|
2021-08-11 04:50:38 -04:00
|
|
|
}
|