overleaf-cep/services/web/frontend/js/infrastructure/tracking-loader.ts
Antoine Clausse 00d5d879c5 [web] Add third-party tracking Propensity (#26638)
* Rename `suppressGoogleAnalytics` to `suppressAnalytics`

* Add Propensity script

* Add LinkedIn Insight Tag script

* Version the cookie to prevent adding unconsented tracking

* Move tracking loaders to Typescript, insert them in foot_scripts.pug

* Show the cookie-banner when tracking other than GA is set

* Revert `oa` cookie versioning

* Remove `async` from propensity script

* Use shared tracking loader for Hotjar, LinkedIn, and Propensity

* Reusable `insertScript`

* Remove tracking-linkedin

* Test the scripts by adding fake ids

* Revert "Test the scripts by adding fake ids"

This reverts commit 50759bb6b40fd2684d1b967d83dd71e8517c3de9.

GitOrigin-RevId: 2a7b36bfc70ac1fc983f837dd4693a19a385cbc6
2025-06-30 08:05:52 +00:00

55 lines
1.2 KiB
TypeScript

import { debugConsole } from '@/utils/debugging'
export const createTrackingLoader = (cb: () => void, name: string) => {
// avoid inserting twice
let initialized = false
const loadTracking = () => {
// consent needed
const consent = document.cookie.split('; ').some(item => item === 'oa=1')
if (initialized || !consent) {
return
}
debugConsole.log('Loading Analytics', name)
initialized = true
cb()
}
// load when idle, if supported
if (typeof window.requestIdleCallback === 'function') {
window.requestIdleCallback(loadTracking)
} else {
loadTracking()
}
// listen for consent
window.addEventListener('cookie-consent', event => {
if ((event as CustomEvent<boolean>).detail) {
loadTracking()
}
})
}
export const insertScript = (attr: {
src: string
crossorigin?: string
async?: boolean
onload?: () => void
}) => {
const script = document.createElement('script')
script.setAttribute('src', attr.src)
if (attr.crossorigin) {
script.setAttribute('crossorigin', attr.crossorigin)
}
if (attr.async) {
script.setAttribute('async', 'async')
}
if (attr.onload) {
script.onload = attr.onload
}
document.querySelector('head')?.append(script)
}