Recently google analytics announced that it gonna end support for old google analytics and want webmasters to move to google analytics 4 (GA4)
So they provide basic google analytics code to track website visitors, but Average User Engagement is not even 1 Minute for my website because it is an online chat room, once the chat loads in iframe the events are not tracked by google analytics.
This is my old google analytics code with heart beat to send signal to google analytics that the user is still active on the site.
<script>(function(d,e,j,h,f,c,b){d.GoogleAnalyticsObject=f;d[f]=d[f]||function(){(d[f].q=d[f].q||[]).push(arguments)},d[f].l=1*new Date();c=e.createElement(j),b=e.getElementsByTagName(j)[0];c.async=1;c.src=h;b.parentNode.insertBefore(c,b)})(window,document,"script","https://www.google-analytics.com/analytics.js","ga");ga("create","UA-Google Analytics Code Goes Here-1","auto");ga("send","pageview");function ga_heartbeat(){console.log("Firing heartbeat");ga("send","event","heartbeat");setTimeout(ga_heartbeat,5*60*1000)}ga_heartbeat();</script>
But in new GA4 it is not possible, so i want to add heart beat for GA4 analytic code, if someone help me it might be useful. Thanks
You can achieve the same with GA4:
<script>
(function ga4_heartbeat(){console.log("Firing heartbeat");gtag("event","heartbeat");setTimeout(ga4_heartbeat,5*60*1000)}());
</script>
given that you use the "Global Site tag (gtag.js)" code from Admin ... Data Streams ... Tagging Instructions ...
Complete Example (replace G-XXX with your own Measurement ID):
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXX');
(function ga4_heartbeat(){console.log("Firing heartbeat");gtag("event","heartbeat");setTimeout(ga4_heartbeat,5*60*1000)}());
</script>