|
| 1 | +const trackingID = '<TO_REPLACE>'; |
| 2 | + |
| 3 | +const GANTED_COOKIE = '__gitbook_cookie_granted'; |
| 4 | + |
| 5 | +function getCookie(cname) { |
| 6 | + const name = `${cname}=`; |
| 7 | + const decodedCookie = decodeURIComponent(document.cookie); |
| 8 | + const ca = decodedCookie.split(';'); |
| 9 | + for (let i = 0; i < ca.length; i++) { |
| 10 | + let c = ca[i]; |
| 11 | + while (c.charAt(0) === ' ') { |
| 12 | + c = c.substring(1); |
| 13 | + } |
| 14 | + if (c.indexOf(name) === 0) { |
| 15 | + return c.substring(name.length, c.length); |
| 16 | + } |
| 17 | + } |
| 18 | + return ''; |
| 19 | +} |
| 20 | + |
| 21 | +function triggerView(win) { |
| 22 | + win.gtag('event', 'page_view', { |
| 23 | + page_path: win.location.pathname, |
| 24 | + page_location: win.location.href, |
| 25 | + page_title: win.document.title, |
| 26 | + send_to: 'tracking_views', |
| 27 | + }); |
| 28 | +} |
| 29 | + |
| 30 | +(function (win, doc, script, layer, id) { |
| 31 | + let disableCookies = false; |
| 32 | + const cookie = getCookie(GANTED_COOKIE); |
| 33 | + if (cookie === 'yes') { |
| 34 | + disableCookies = false; |
| 35 | + } else if (cookie === 'no') { |
| 36 | + disableCookies = true; |
| 37 | + } |
| 38 | + |
| 39 | + win[layer] = win[layer] || []; |
| 40 | + win.gtag = function () { |
| 41 | + // eslint-disable-next-line prefer-rest-params |
| 42 | + win[layer].push(arguments); |
| 43 | + }; |
| 44 | + |
| 45 | + win.gtag('js', new Date()); |
| 46 | + win.gtag('config', id); |
| 47 | + win.gtag('consent', 'default', { |
| 48 | + ad_storage: disableCookies ? 'denied' : 'granted', |
| 49 | + analytics_storage: disableCookies ? 'denied' : 'granted', |
| 50 | + }); |
| 51 | + const f = doc.getElementsByTagName(script)[0], |
| 52 | + j = doc.createElement(script), |
| 53 | + dl = layer !== 'dataLayer' ? `&l=${layer}` : ''; |
| 54 | + j.async = true; |
| 55 | + j.src = `https://www.googletagmanager.com/gtag/js?id=${id}${dl}`; |
| 56 | + j.onload = function () { |
| 57 | + win.gtag('config', id, { |
| 58 | + send_page_view: false, |
| 59 | + anonymize_ip: true, |
| 60 | + groups: 'tracking_views', |
| 61 | + }); |
| 62 | + triggerView(win); |
| 63 | + |
| 64 | + win.history.pushState = new Proxy(win.history.pushState, { |
| 65 | + apply: (target, thisArg, argArray) => { |
| 66 | + triggerView(win); |
| 67 | + return target.apply(thisArg, argArray); |
| 68 | + }, |
| 69 | + }); |
| 70 | + }; |
| 71 | + f.parentNode.insertBefore(j, f); |
| 72 | +})(window, document, 'script', 'dataLayer', trackingID); |
0 commit comments