我想创建一个函数,仅在访问者同意时触发GA4测量。 我已经按照以下方式创建了它:
问题在于 TypeScript 报告错误:
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;
})
问题在于 TypeScript 报告错误:
“Property 'dataLayer' does not exist on type 'Window & typeof globalThis
a gtag - Expected 0 arguments, but got 2
”。
我已经尝试了各种教程,并安装了@types/gtag.js
,但错误仍然存在。请问我做错了什么?谢谢。