UNPKG

@bemit/consent-ui

Version:

© 2022 [bemit](https://bemit.eu)

52 lines 1.38 kB
const gtagState = { loaded: false }; window.gtag = function () { window.dataLayer?.push(arguments); }; export const loadGtag = (googleTracking, cb) => { const scriptGa = document.createElement('script'); scriptGa.async = true; scriptGa.src = 'https://www.googletagmanager.com/gtag/js?id=' + googleTracking; scriptGa.onload = cb; document.body.append(scriptGa); }; export const pluginGoogle = (group, googleTracking) => ({ shouldBe: options => { return Boolean(options?.groups?.[group]); }, create: wasAlreadyCreated => { if (wasAlreadyCreated) return; let tmpLayer = []; if (!gtagState.loaded) { tmpLayer = [...(window.dataLayer || [])]; window.dataLayer = []; } const cb = () => { window.gtag?.('js', new Date()); window.gtag?.('config', googleTracking, { 'anonymize_ip': true, 'transport_type': 'beacon', 'send_page_view': false }); window.gtag?.('event', 'page_view', { 'page_title': document.title, 'page_location': window.location.toString() }); tmpLayer.forEach(function (elem) { window.dataLayer.push(elem); }); }; if (!gtagState.loaded) { gtagState.loaded = true; loadGtag(googleTracking, cb); } else { cb(); } }, destroy: () => { return { requiresRefresh: true }; } });