Reputation: 221
This is my code related to Google Analytics in my header:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-ID"> </script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-ID');
</script>
This is the code inside my JavaScript file included at the bottom:
// Send Google Analytics data if the cookie does not exist
if (document.cookie.indexOf("internalTest=") === -1) {
window.ga = window.ga || function () {
(ga.q = ga.q || []).push(arguments)
};
ga.l = +new Date;
ga('create', 'UA-ID', 'auto');
ga('send', 'pageview');
}
The cookie homeTest
exists on my laptop but it still shows in real time data in Analytics.
What am I doing wrong?
Thanks.
Upvotes: 1
Views: 178
Reputation: 5545
You are using a mixture of gtag.js
and analytics.js
.
The function gtag('config', 'UA-ID');
is already sending a pageview by default. Instead of this use something like thisgtag('config', 'GA_TRACKING_ID', { 'send_page_view': false });
to prevent the pageview from being sent automatically.
For more information about working with gtag.js
, refer to their documentation.
If your setup heavily depends on analytcs.js
(still perfectly supported by Google), just switch your analytics snippet to something like this
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
When doing a completely new setup, Google recommends using gtag.js
.
The easiest solution in your case would be putting the gtag('config', 'UA-ID');
in your if statement.
Upvotes: 3