Add Analytics

This commit is contained in:
2022-06-23 19:04:23 +02:00
parent aea65da747
commit c66fe85879
3 changed files with 67 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
<script lang="ts">
// @ts-nocheck
import { page } from '$app/stores'
import { sendPage } from '../utils/analytics'
export let appKey: any
export let url: any
export let enabled: boolean = process.env.NODE_ENV !== 'development'
let loaded = false
const handleLoad = () => {
// Init Countly
if (Countly) {
Countly.init({
app_key: appKey,
url,
})
Countly.track_sessions()
Countly.track_pageview()
}
loaded = true
}
// Send page to Analytics when changing path
$: enabled && $page.url.pathname && loaded && sendPage()
</script>
<svelte:head>
{#if enabled}
<script defer src="https://cdn.jsdelivr.net/npm/countly-sdk-web@latest/lib/countly.min.js" on:load={handleLoad} />
{/if}
</svelte:head>
<noscript>
<img src="{url}/pixel.png?app_key={appKey}&begin_session=1" alt="countly" width="0" height="0" />
</noscript>

View File

@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import '../style/global.scss' import '../style/global.scss'
import { browser } from '$app/env'
import { navigating, page } from '$app/stores' import { navigating, page } from '$app/stores'
import { beforeNavigate } from '$app/navigation' import { beforeNavigate } from '$app/navigation'
import { onMount, setContext } from 'svelte' import { onMount, setContext } from 'svelte'
@@ -9,6 +10,7 @@
import '$utils/polyfills' import '$utils/polyfills'
// Components // Components
import SVGSprite from '$components/SVGSprite.svelte' import SVGSprite from '$components/SVGSprite.svelte'
import Analytics from '$components/Analytics.svelte'
import Switcher from '$components/molecules/Switcher.svelte' import Switcher from '$components/molecules/Switcher.svelte'
import Footer from '$components/organisms/Footer.svelte' import Footer from '$components/organisms/Footer.svelte'
@@ -63,6 +65,13 @@
<SVGSprite /> <SVGSprite />
{#if browser}
<Analytics
appKey={import.meta.env.VITE_ANALYTICS_KEY}
url={import.meta.env.VITE_ANALYTICS_URL}
/>
{/if}
<script context="module" lang="ts"> <script context="module" lang="ts">
import type { LoadEvent, LoadOutput } from '@sveltejs/kit' import type { LoadEvent, LoadOutput } from '@sveltejs/kit'

21
src/utils/analytics.ts Normal file
View File

@@ -0,0 +1,21 @@
// @ts-nocheck
// Send page
export const sendPage = (path: string) => {
if (Countly) {
Countly.track_pageview()
}
}
// Send event
export const sendEvent = ({ action, segments = {}, amount = 1 }) => {
if (Countly) {
Countly.add_event({
key: action,
count: amount,
segmentation: {
...segments
}
})
}
}