Adrien Denat pierric HF staff commited on
Commit
572bb0e
β€’
1 Parent(s): b2387f6

πŸ“ˆ Add GTM (#119)

Browse files

* add GTM

following Hub setup

* update comment link for GA v4

Co-authored-by: Pierric Cistac <Pierrci@users.noreply.github.com>

---------

Co-authored-by: Pierric Cistac <Pierrci@users.noreply.github.com>

Files changed (2) hide show
  1. src/app.html +20 -0
  2. src/lib/utils/analytics.ts +39 -0
src/app.html CHANGED
@@ -17,5 +17,25 @@
17
  </head>
18
  <body data-sveltekit-preload-data="hover" class="h-full dark:bg-gray-900">
19
  <div class="contents h-full">%sveltekit.body%</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  </body>
21
  </html>
 
17
  </head>
18
  <body data-sveltekit-preload-data="hover" class="h-full dark:bg-gray-900">
19
  <div class="contents h-full">%sveltekit.body%</div>
20
+
21
+ <!-- Google Tag Manager -->
22
+ <script>
23
+ if (["hf.co", "huggingface.co"].includes(window.location.hostname)) {
24
+ const script = document.createElement("script");
25
+ script.src = "https://www.googletagmanager.com/gtag/js?id=G-8Q63TH4CSL";
26
+ script.async = true;
27
+ document.head.appendChild(script);
28
+
29
+ window.dataLayer = window.dataLayer || [];
30
+ function gtag() {
31
+ dataLayer.push(arguments);
32
+ }
33
+ gtag("js", new Date());
34
+ /// ^ See https://developers.google.com/tag-platform/gtagjs/install
35
+ gtag("consent", "default", { ad_storage: "denied", analytics_storage: "denied" });
36
+ /// ^ See https://developers.google.com/tag-platform/gtagjs/reference#consent
37
+ /// TODO: ask the user for their consent and update this with gtag('consent', 'update')
38
+ }
39
+ </script>
40
  </body>
41
  </html>
src/lib/utils/analytics.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface GAEvent {
2
+ hitType: "event";
3
+ eventCategory: string;
4
+ eventAction: string;
5
+ eventLabel?: string;
6
+ eventValue?: number;
7
+ }
8
+
9
+ // Send a Google Analytics event
10
+ export function sendAnalyticsEvent({
11
+ eventCategory,
12
+ eventAction,
13
+ eventLabel,
14
+ eventValue,
15
+ }: Omit<GAEvent, "hitType">): void {
16
+ // Mandatory fields
17
+ const event: GAEvent = {
18
+ hitType: "event",
19
+ eventCategory,
20
+ eventAction,
21
+ };
22
+ // Optional fields
23
+ if (eventLabel) {
24
+ event.eventLabel = eventLabel;
25
+ }
26
+ if (eventValue) {
27
+ event.eventValue = eventValue;
28
+ }
29
+
30
+ // @ts-expect-error typescript doesn't know gtag is on the window object
31
+ if (!!window?.gtag && typeof window?.gtag === "function") {
32
+ // @ts-expect-error typescript doesn't know gtag is on the window object
33
+ window?.gtag("event", eventAction, {
34
+ event_category: event.eventCategory,
35
+ event_label: event.eventLabel,
36
+ value: event.eventValue,
37
+ });
38
+ }
39
+ }