在NextJS 13应用程序目录中实现Google Analytics

7kjnsjlb  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(164)

有没有人试图在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,所以我被困在那里.
有人能解释为什么会这样吗?

rjee0c15

rjee0c151#

我的方式使用谷歌分析与下一个应用程序目录
/components/GoogleAnalytics.tsx

"use client";
    
    import Script from "next/script";
    import * as gtag from "@/lib/gtag";
    
    const GoogleAnalytics = () => {
      return (
        <>
          <Script
            strategy='afterInteractive'
            src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
          />
          <Script
            id='gtag-init'
            strategy='afterInteractive'
            dangerouslySetInnerHTML={{
              __html: `
                          window.dataLayer = window.dataLayer || [];
                          function gtag(){dataLayer.push(arguments);}
                          gtag('js', new Date());
                          gtag('config', '${gtag.GA_TRACKING_ID}', {
                          page_path: window.location.pathname,
                          });
                        `,
            }}
          />
        </>
      );
    };

    
    export default GoogleAnalytics;

app/layout.tsx

import "@/styles/globals.css";
    import GoogleAnalytics from "@/components/GoogleAnalytics";
    
    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode;
    }) {
      return (
        <html lang='fr'>
          <body>
            <main>
                    <GoogleAnalytics />
                        {children}
                  </main>
          </body>
        </html>
      );
    }

lib/gtag.ts

export const GA_TRACKING_ID: string | undefined = process.env.GA_TRACKING_ID;
    
    export const pageview = (url: string) => {
      (window as any).gtag("config", GA_TRACKING_ID, {
        page_path: url,
      });
    };
    
    export const event = ({
      action,
      category,
      label,
      value,
    }: {
      action: string;
      category: string;
      label: string;
      value: number;
    }) => {
      (window as any).gtag("event", action, {
        event_category: category,
        event_label: label,
        value: value,
      });
    };

相关问题