我在我的网站上使用Osano Cookie Consent插件。它显示一个横幅,使用以下代码片段启用或禁用使用谷歌分析进行跟踪:
window.addEventListener("load", function(){
window.cookieconsent.initialise({
"type": "opt-out",
"content": {
"message": "This website uses cookies",
"allow": "Allow all cookies",
"deny": "Deny all cookies"
},
onInitialise: function (status) {
var didConsent = this.hasConsented();
if (!didConsent) {
gaOptout();
}
},
onStatusChange: function (status, chosenBefore) {
var didConsent = this.hasConsented();
if (!didConsent) {
gaOptout();
}
if (didConsent) {
enableCookies();
}
}
})});
</script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script>
var gaProperty = 'UA-128681096-1';
// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
window[disableStr] = true;
}
// Opt-out function
function gaOptout() {
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[disableStr] = true;
}
// Opt-in function
function enableCookies() {
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments)
}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-X', { 'anonymize_ip': true });
window[disableStr] = false;
}
</script>
这按预期工作。但是,在网站上的一个地方,我正在跟踪用户事件,当单击模式时,如下所示:
<a onclick="gtag('event', 'EventName', { 'event_category': 'CV', 'event_label': 'clicked' });">
单击该链接会返回错误消息:
未捕获的类型错误:无法读取 HTMLAnchorElement.onclick 处未定义的属性“gtag”
我猜会发生这种情况,因为 gtag 函数在 enableCookies 函数范围内。所以我尝试的是:
var outerFunction = enableCookies();
<a onclick="outerFunction.gtag('event', 'EventName', { 'event_category': 'CV', 'event_label': 'clicked' });">
不幸的是,这确实返回了同样的错误。
我会非常感谢任何形式的帮助!