I want to create a function that triggers a GA4 measurement only when the visitor agrees. I created it as follows:
document.querySelector('.cookie').addEventListener('click', function(){
var ga = document.createElement('script')
ga.type = 'text/javascript'
ga.async = true
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.googletagmanager.com/gtag/js?id=UA-XXXXXX-X'
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
let gat = window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXX-X');
setCookie('cookie','1',365);
return false;
})
The problem is that typescript reports errors: Property 'dataLayer' does not exist on type 'Window & typeof globalThis
a gtag - Expected 0 arguments, but got 2
.
I've tried various tutorials, installed @types/gtag.js
, but the errors persist. Can you advise me what I'm doing wrong? Thank you