I'm looking for the right way to set up google analytics in my sveltekit application.
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
window.dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'TRACKING_ID');
</script>
__layout.svelte
$: {
console.log('page: ' + $page.url.pathname);
if (typeof gtag !== 'undefined') {
console.log('callign gtag: ' + $page.url.pathname);
gtag('config', trackingId, {
page_path: $page.url.pathname
});
}
}
It works fine the only problem is a double reporting
I can see a page twice instead of once :(
Can help me, please?
I use this script. I found it from a Youtuber but I don't remember the channel to reference.
I import it to __layout.svelte. This helps to initiate the gtag on Production and reference visited pages correctly.
<script>
import { page } from '$app/stores';
$: if (typeof gtag !== 'undefined' && import.meta.env.PROD == true) {
if ($page.query.toString().length > 0) {
gtag('config', 'GA_MEASUREMENT_ID', {
page_path : $page.path,
page_location: `${$page.host}${$page.path}?${$page.query}`,
});
} else {
gtag('config', 'GA_MEASUREMENT_ID', {
page_path : $page.path,
page_location: `${$page.host}${$page.path}`,
});
}
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With