✨ Add Analytics
This commit is contained in:
37
src/components/Analytics.svelte
Normal file
37
src/components/Analytics.svelte
Normal 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>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import '../style/global.scss'
|
||||
|
||||
import { browser } from '$app/env'
|
||||
import { navigating, page } from '$app/stores'
|
||||
import { beforeNavigate } from '$app/navigation'
|
||||
import { onMount, setContext } from 'svelte'
|
||||
@@ -9,6 +10,7 @@
|
||||
import '$utils/polyfills'
|
||||
// Components
|
||||
import SVGSprite from '$components/SVGSprite.svelte'
|
||||
import Analytics from '$components/Analytics.svelte'
|
||||
import Switcher from '$components/molecules/Switcher.svelte'
|
||||
import Footer from '$components/organisms/Footer.svelte'
|
||||
|
||||
@@ -63,6 +65,13 @@
|
||||
|
||||
<SVGSprite />
|
||||
|
||||
{#if browser}
|
||||
<Analytics
|
||||
appKey={import.meta.env.VITE_ANALYTICS_KEY}
|
||||
url={import.meta.env.VITE_ANALYTICS_URL}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
|
||||
<script context="module" lang="ts">
|
||||
import type { LoadEvent, LoadOutput } from '@sveltejs/kit'
|
||||
|
||||
21
src/utils/analytics.ts
Normal file
21
src/utils/analytics.ts
Normal 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
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user