admin管理员组文章数量:1302274
I am trying to block google analytics in javascript when a user don't want to get cookies.
if (want_cookie != "no"){
/* load google analytics script */
}
But I didn't find how to load this script in javascript ...
<script async src=""></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXX');
</script>
I am trying to block google analytics in javascript when a user don't want to get cookies.
if (want_cookie != "no"){
/* load google analytics script */
}
But I didn't find how to load this script in javascript ...
<script async src="https://www.googletagmanager./gtag/js?id=UA-XXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXX');
</script>
Share
Improve this question
asked Jul 3, 2018 at 12:24
Arthur HArthur H
531 silver badge5 bronze badges
2 Answers
Reset to default 9Try something like this:
if (want_cookie != "no"){
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", "https://www.googletagmanager./gtag/js?id=UA-XXXXXX");
document.documentElement.firstChild.appendChild(newScript);
}
So what I did is after checking if user agree on cookies dynamically create script element and append it to page.
Building on top of the accepted answer, I implemented it like this:
HTML:
<button id="declineButton">Decline</button>
<button id="acceptButton">Accept</button>
JS for declining:
declineButton.addEventListener("click", () => {
window["ga-disable-G-XXXX"] = true; // replace G-XXXX with your id
});
JS for accepting:
acceptButton.addEventListener("click", () => {
window["ga-disable-G-XXXX"] = false; // replace G-XXXX with your id
appendScriptToHead();
executeGoogleAnalyticsScript();
});
function appendScriptToHead() {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "https://www.googletagmanager./gtag/js?id=G-XXXX"; // replace G-XXXX with your ID
document.head.appendChild(script);
}
function executeGoogleAnalyticsScript() {
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-XXXX"); // replace G-XXXX with your id
}
Note:
According to the documentation we have to make sure that the disabling (setting the window property) is done before the gtag()
is executed.
本文标签: cookiesHow to load gtagjs (Google analytics) dynamically in javascriptStack Overflow
版权声明:本文标题:cookies - How to load gtag.js (Google analytics) dynamically in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741648700a2390343.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论