在访问者接受使用页面正文后实施 Google 分析脚本

Implementing Google Analytics Script AFTER the Visitor Accept Using Body of Page

目的很简单,运行 在用户接受后 google 跟踪代码,如果用户不接受,则不 运行。

我将代码放在标签内,但我很难理解如何合并“关闭”选项。

这是我目前的“进行中”代码:

<script>
(function() {
    if (!localStorage.getItem('cookieconsent')) {
        document.body.innerHTML += '\
        <div class="cookieconsent" style="position:fixed;padding:20px;left:0;bottom:0;background-color:#000;color:#FFF;text-align:center;width:100%;z-index:99999;">\
            This site uses standard cookies and Google Analytics. By clicking on "I understand", you agree to their use. \
            <a href="#" style="color:#CCCCCC;font-weight:bold;">I Understand</a>\
        </div>\
        ';
        document.querySelector('.cookieconsent a').onclick = function(e) {
            e.preventDefault();
            document.querySelector('.cookieconsent').style.display = 'none';
            localStorage.setItem('cookieconsent', true);
        };
    }
})();
</script>

据我了解,我需要在这一行之后放置 google 跟踪:

localStorage.setItem('cookieconsent', true);

但是脚本标签已经打开了,我该怎么做呢?

跟踪代码示例:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXX');
</script>

除此之外,我不确定如何添加关闭选项以使 google 代码不会 运行。我很感激我能得到的所有意见。

这可能包含您问题的答案Consent Mode (beta)

“同意模式(测试版)允许您根据用户的同意状态调整您的 Google 标签的行为方式。您可以指明是否同意分析和广告 cookie。Google 的标签将动态调整,仅在用户同意后才将测量工具用于特定目的。"