'Adding Google analytics with consent manager to a SvelteKit website
I need to add Google Analytics to a SvelteKit website. The instructions from Google is that the script below should be added to the <head> tag, so I thought that I could just add it in app.html. The problem is that I need to use Consent Mode to follow GDPR regulations. To do that, I need to be able to read and write to some kind of variable to enable and disable analytics.
As far as I can tell, I can't access any variables from within the <head> tag. I also tried adding the same code to a <svelte:head> tag in __layout.svelte, but it seems like I can't access variables there either.
I plan on tracking the cookie consent using a store, and persisting that value to local storage, but I am open to other solutions as well.
Here is the code that should be added to the <head> tag:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-H5XGB0JC8S"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-H5XGB0JC8S');
</script>
Here is the code that has to be added to disable analytics:
gtag('consent', 'default', {
analytics_storage: 'denied',
ad_storage: 'denied'
});
And here is the code to call to update a value:
gtag('consent', 'update', {
'ad_storage': 'granted'
});
I assume that the last code snippet should be called when the accept button is pressed, but if I call gtag from anywhere else other than the same place as the first code snippet, I get a warning saying that the function is not defined.
Should I add the code somewhere else, or should it be done in some other way?
Maybe I should mention that I am using TypeScript as well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
