有没有人试图在NextJS 13应用程序目录中实现Google Analytics 4(gtag)?在我以前的Vanilla JS / EJS应用程序中,我只需要将以下代码添加到每个页面。所以我的理解是,在每个页面初始化时,这段代码会向谷歌分析发送一个page_view事件。
<script> src={`https://www.googletagmanager.com/gtag/js?id=GAID`} <script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GAID', {foo: bar}); // Where bar is a variable depending on the page
</script>
我在互联网上找到了一些类似的博客,但没有在配置中实现变量的情况。我尝试了以下方法,但没有一个成功。
在做这些之前,我已经在next/script中应用了
1.将此代码放入layout.tsx中
1.将此代码放入template.tsx中
1.把这段代码放在第.tsx页
1.将此代码放在每个页面的第一个客户端组件中。
1.将gtag('js')和gtag('config')集成到一个函数中,并在上面的页面中调用window. jsgga(bar)。
<script> src={`https://www.googletagmanager.com/gtag/js?id=GAID`} <script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
function configGA(bar) {
gtag('js', new Date());
gtag('config', 'GAID', {foo: bar}); // Where bar is a variable depending on the page
}
</script>
然而,所有这些试验都只返回相同的结果:{foo:bar}其中bar是整个应用程序加载的初始条。例如,当我第一次进入主页时,有一个带有bar 1的page_view事件。当我点击到页面A时,它仍然给我bar 1。然后无论我去哪里,它给我bar 1,除非我重新加载页面。
我在网上查了一下,人们使用next/router来解决这个问题,但是在NextJS 13中没有next/router,所以我被困在那里.
有人能解释为什么会这样吗?
1条答案
按热度按时间rjee0c151#
我的方式使用谷歌分析与下一个应用程序目录
/components/GoogleAnalytics.tsx
app/layout.tsx
lib/gtag.ts