Add GA tracking

astro
Kamran Ahmed 2 years ago
parent 9dbb2d05c9
commit c359aefdac
  1. 16
      src/components/Analytics/Analytics.astro
  2. 53
      src/components/Analytics/analytics.ts
  3. 8
      src/layouts/BaseLayout.astro

@ -0,0 +1,16 @@
---
---
<script src='./analytics.js'></script>
<script async src='https://www.googletagmanager.com/gtag/js?id=UA-139582634-1'
></script>
<script>
// @ts-nocheck
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'UA-139582634-1');
</script>

@ -0,0 +1,53 @@
export {};
declare global {
interface Window {
gtag: any;
fireEvent: (props: EventType) => void;
firePageView: (url: string) => void;
}
}
/**
* Tracks the page view on google analytics
* @see https://developers.google.com/analytics/devguides/collection/gtagjs/pages
* @param url URL to track
* @returns void
*/
window.firePageView = (url: string) => {
if (!window.gtag) {
console.warn('Missing GTAG - Analytics disabled');
return;
}
window.gtag('config', 'UA-139582634-1', {
page_path: url,
});
};
type EventType = {
action: string;
category: string;
label?: string;
value?: string;
};
/**
* Tracks the event on google analytics
* @see https://developers.google.com/analytics/devguides/collection/gtagjs/events
* @param props Event properties
* @returns void
*/
window.fireEvent = (props: EventType) => {
const { action, category, label, value } = props;
if (!window.gtag) {
console.warn('Missing GTAG - Analytics disabled');
return;
}
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
});
};

@ -7,6 +7,7 @@ import type { SponsorType } from '../components/Sponsor/Sponsor.astro';
import Sponsor from '../components/Sponsor/Sponsor.astro';
import YouTubeBanner from '../components/YouTubeBanner.astro';
import { siteConfig } from '../lib/config';
import Analytics from '../components/Analytics/Analytics.astro';
export interface Props {
title: string;
@ -34,7 +35,10 @@ const {
<meta name='description' content={description} />
<meta name='author' content='Kamran Ahmed' />
<meta name='keywords' content={keywords.join(', ')} />
{noIndex && <meta name='robots' content='noindex' />}
<!-- TODO: Add when launching -->
<!-- {noIndex && <meta name='robots' content='noindex' />} -->
<!-- TODO: Remove when launching -->
<meta name='robots' content='noindex' />
<meta
name='viewport'
content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0'
@ -93,6 +97,8 @@ const {
<link rel='icon' href='/manifest/favicon.ico' type='image/x-icon' />
<slot name='after-header' />
<Analytics />
</head>
<body>
<YouTubeBanner />

Loading…
Cancel
Save