Skip to content

Commit

Permalink
Init tracker after matomo script load (#1127)
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperengstrom authored Oct 21, 2024
1 parent b183f09 commit 8986834
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
19 changes: 14 additions & 5 deletions lxl-web/src/lib/components/Matomo.svelte
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
<script lang="ts">
import { env } from '$env/dynamic/public';
import { afterNavigate } from '$app/navigation';
import { setMatomoTracker, getMatomoTracker } from '$lib/contexts/matomo';
import { setMatomoTracker, getMatomoTracker, setMatomoContext } from '$lib/contexts/matomo';
const URL: string = env.PUBLIC_MATOMO_URL;
setMatomoTracker();
setMatomoContext();
const tracker = getMatomoTracker();
afterNavigate(async ({ to, from }) => {
function onMatomoScriptLoad() {
if (!$tracker) {
setMatomoTracker();
}
}
afterNavigate(async ({ to, from, type }) => {
if ($tracker) {
if (from?.url.href) {
$tracker.setReferrerUrl(from.url.href);
}
if (to?.url.href) {
$tracker.setCustomUrl(to.url.href);
}
$tracker.trackPageView(document.title);
if (type !== 'enter') {
// First track is done on init (when script is ready)
$tracker.trackPageView(document.title);
}
}
});
</script>

<svelte:head>
{#if URL}
<script async defer src={`${URL}/matomo.js`}></script>
<script async defer src={`${URL}/matomo.js`} on:load={onMatomoScriptLoad}></script>
{/if}
</svelte:head>
<slot />
12 changes: 10 additions & 2 deletions lxl-web/src/lib/contexts/matomo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { setContext, getContext } from 'svelte';

const MATOMO_ID: number = +env.PUBLIC_MATOMO_ID;

const tracker = writable<MatomoTracker>();

function initMatomo() {
if (browser) {
const matomo = window.Matomo;
Expand All @@ -16,6 +18,7 @@ function initMatomo() {
if (tracker) {
tracker.disableCookies(); // TODO - remove when cookie consent implemented
tracker.enableLinkTracking();
tracker.trackPageView();
return tracker;
}
}
Expand All @@ -25,11 +28,16 @@ function initMatomo() {
export function setMatomoTracker() {
const initializedMatomoTracker = initMatomo();
if (initializedMatomoTracker) {
const tracker = writable<MatomoTracker>(initializedMatomoTracker);
setContext('matomo', tracker);
tracker.set(initializedMatomoTracker);
console.info('Matomo tracker set');
}
}

export function setMatomoContext() {
setMatomoTracker();
setContext('matomo', tracker);
}

export function getMatomoTracker() {
return getContext<Writable<MatomoTracker>>('matomo');
}

0 comments on commit 8986834

Please sign in to comment.