Google Analytics 4与Next js

nc1teljy  于 2023-06-22  发布在  Go
关注(0)|答案(1)|浏览(145)

我遇到的问题是,我试图将Google Analytics添加到My Next.js应用程序中,有两个问题。第一个问题是我在Chrome的网络选项卡中看不到收集消息,但在Microsoft Edge中可见。此外,Chrome中的dataLayer在登录到控制台时不显示任何事件,而Edge显示事件。第二个问题是,我仍然有“没有收到数据”在我的谷歌分析 Jmeter 板和实时不显示任何东西。这是我的code_app. js

import "@/styles/globals.css";
import { appWithTranslation } from "next-i18next";
import { Raleway } from "next/font/google";
import Head from "next/head";
import Script from "next/script";
import dynamic from "next/dynamic";

import GoogleAnalytics from "@/components/GoogleAnalyitics";
const CookieBanner = dynamic(() => import("../components/CookieBanner"), {
  ssr: false,
});
const raleway = Raleway({
  subsets: ["latin"],
  variable: "--font-ral",
});
const ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS;
function App({ Component, pageProps }) {
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.png" />
      </Head>

      <main className={`${raleway.variable} font-ral min-h-screen w-full`}>
        <Component {...pageProps} />
        <CookieBanner></CookieBanner>
        <Script id="tawk" strategy="lazyOnload">
          {`var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
         (function(){
           var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
           s1.async=true;
           s1.src='https://embed.tawk.to/64367ade4247f20fefeb2cc2/1gtqcvtgf';
           s1.charset='UTF-8';
           s1.setAttribute('crossorigin','*');
           s0.parentNode.insertBefore(s1,s0);
           })()`}
        </Script>
        <GoogleAnalytics GA_MEASUREMENT_ID={ID}></GoogleAnalytics>
      </main>
    </>
  );
}

export default appWithTranslation(App);

GoogleAnalytics.js

import Script from "next/script";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { pageview } from "@/lib/gtagHelper";
export default function GoogleAnalytics({ GA_MEASUREMENT_ID }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    const url = pathname + searchParams.toString();

    pageview(GA_MEASUREMENT_ID, url);
  }, [pathname, searchParams, GA_MEASUREMENT_ID]);
  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('consent', 'default', {
                    'analytics_storage': 'denied'
                });
                
                gtag('config', '${GA_MEASUREMENT_ID}', {
                    page_path: window.location.pathname,
                });
                `,
        }}
      />
    </>
  );
}

gtagHelper.js

export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS;

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
  window.gtag("config", GA_TRACKING_ID, {
    page_path: url,
  });
};

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
  window.gtag("event", action, {
    event_category: category,
    event_label: label,
    value: value,
  });
};

CookieBanner.js

import Link from "next/link";
import { getLocalStorage, setLocalStorage } from "@/lib/storageHelper";
import { useState, useEffect } from "react";
export default function CookieBanner() {
  const [cookieConsent, setCookieConsent] = useState(false);

  useEffect(() => {
    const storedCookieConsent = getLocalStorage("cookie_consent", null);

    setCookieConsent(storedCookieConsent);
  }, [setCookieConsent]);

  useEffect(() => {
    const newValue = cookieConsent ? "granted" : "denied";

    window.gtag("consent", "update", {
      analytics_storage: newValue,
    });

    setLocalStorage("cookie_consent", cookieConsent);
  }, [cookieConsent]);
  return (
    <div
      className={`${
        cookieConsent !== null ? "hidden" : "flex"
      } my-10 mx-auto w-max fixed bottom-0 left-0 right-0  px-3 md:px-4 py-3 justify-between items-center flex-col sm:flex-row gap-4 bg-gray-200 rounded-lg shadow`}
    >
      <div className="text-center">
        <Link href="/info/cookies">
          <p className="whitespace-nowrap">
            We use{" "}
            <span className="font-bold text-sky-400 mx-1"> cookies </span> on
            our site.
          </p>
        </Link>
      </div>

      <div className="flex gap-2">
        <button
          onClick={() => setCookieConsent(false)}
          className="px-5 py-2 text-gray-700 rounded-md border-gray-900"
        >
          Decline
        </button>
        <button
          onClick={() => setCookieConsent(true)}
          className="bg-primary px-5 py-2 text-white rounded-lg whitespace-nowrap"
        >
          Allow Cookies
        </button>
      </div>
    </div>
  );
}

我尝试将Google Analyitics添加到我的页面,我希望在Google Analytics Jmeter 板上实时看到变化

kx1ctssn

kx1ctssn1#

不确定这是否会有帮助,但是在你的_app.js代码中,import中有一个错别字:

import GoogleAnalytics from "@/components/GoogleAnalyitics";

最后把“Analytics”拼错了。

相关问题