简而言之
Javascript/jQuery / js-cookie 唯一的解决方案,“仅”部分适用于 GTM(Google 跟踪代码管理器)的情况,因为它具有 <noscript> 实现。请参阅下面的详细信息。
如何
HTML
<span class="js-ga-opt-out">Disable GA - Javascript solution</span>
<span class="js-ga-opt-in">Enable GA - Javascript solution</span>
Javascript
// note that setCookie(key, value) is a custom function
function optOutGoogleTracking(){
setCookie('_ga', undefined);
setCookie('optOutGoogleTracking', true);
alert('disabling GA cookies');
window.location.reload();
}
function optInGoogleTracking(){
setCookie('optOutGoogleTracking', false);
alert('enabling GA cookies');
window.location.reload();
}
$('html').on("click", ".js-ga-opt-out", function(){
optOutGoogleTracking();
});
$('html').on("click", ".js-ga-opt-in", function(){
optInGoogleTracking();
});
Google 跟踪代码管理器脚本
注意<noscript></noscript>标签内的内容不能被Javascript有条件地跳过。
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js"></script>
<!-- Google Tag Manager -->
<noscript>
<iframe src="//www.googletagmanager.com/ns.html?id=GTM-xxxxx"
height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<script>
if(Cookies.get('optOutGoogleTracking') === 'false') { // here is your condition
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-xxxxx');
}
</script>
<!-- End Google Tag Manager -->
我的理解是,<noscript> 标签用于禁用 Javascript 的情况。然后将通过 iframe 进行跟踪。
不过,对于大多数情况,此解决方案可能“足够好”。
这是否符合法律规定?应该不会吧。