如何为 Google Analytics 4 Gtag 设置心跳

How to setup heartbeat for Google Analytics 4 Gtag

最近 google Analytics 宣布将终止对旧 google Analytics 的支持,并希望网站管理员迁移到 google Analytics 4 (GA4)

所以他们提供了基本的 google 分析代码来跟踪网站访问者,但我的网站的平均用户参与度甚至不到 1 分钟,因为它是一个在线聊天室,一旦聊天在 iframe 中加载,事件就会发生google 分析未跟踪。

这是我的旧 google 分析代码,带有心跳以向 google 分析发送信号,表明用户在网站上仍然活跃。

<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>

但是在新的GA4中这是不可能的,所以我想为GA4分析代码添加心跳,如果有人帮助我可能会有用。谢谢

您可以使用 GA4 实现同样的效果:

<script>
(function ga4_heartbeat(){console.log("Firing heartbeat");gtag("event","heartbeat");setTimeout(ga4_heartbeat,5*60*1000)}());
</script>

假定您使用来自 Admin ... Data Streams ... Tagging Instructions ...[= 的“全局站点标签 (gtag.js)”代码12=]

完整示例(将 G-XXX 替换为您自己的测量 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>