add GoogleAnalytics

This commit is contained in:
liangzai 2024-09-20 23:10:37 +08:00
parent 6bf444b164
commit 3a44437f1a
2 changed files with 44 additions and 5 deletions

View File

@ -7,14 +7,10 @@ import { GetMetadata } from "@/apis/auth";
import "./globals.scss";
import Loading from "./loading";
import CombinedProviders from "@/contexts/CombinedProviders";
import GoogleAnalytics from "@/components/GoogleAnalytics";
const inter = Inter({ subsets: ["latin"] });
// export const metadata: Metadata = {
// title: "typeframes",
// description: "Generated by typeframes",
// };
// 将metadata改为异步函数获取动态SEO数据
export async function generateMetadata(): Promise<Metadata> {
const res = await GetMetadata(); // 调用API获取SEO数据
if (res.code === 200) {
@ -50,6 +46,7 @@ async function RootLayout({
<CombinedProviders>{children}</CombinedProviders>
</Suspense>
</NextIntlClientProvider>
<GoogleAnalytics />
</body>
</html>
);

View File

@ -0,0 +1,42 @@
"use client";
import { useEffect } from "react";
import Script from "next/script";
import { usePathname } from "next/navigation";
const GA_TRACKING_ID = "G-JGPW372ZX7"; // 替换为你的Tracking ID
declare global {
interface Window {
gtag: (...args: any[]) => void;
}
}
const GoogleAnalytics = () => {
const pathname = usePathname();
useEffect(() => {
if (typeof window !== "undefined" && GA_TRACKING_ID) {
window.gtag("config", GA_TRACKING_ID, {
page_path: pathname,
});
}
}, [pathname]);
return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
strategy="afterInteractive" // 脚本将在页面加载完成后运行
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}');
`}
</Script>
</>
);
};
export default GoogleAnalytics;