我已经成功地将Google Analytics添加到我的Next.js 13.5项目中,并且它运行良好,向我显示用户正在访问的页面。然而,我遇到了一个自动添加<meta name="robots" content="noindex"/>
标签的问题。因此,当我尝试索引我的网站时,它似乎无法按预期工作。
// GoogleAnalytics
import Script from "next/script";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { pageview } from "@/lib/gtagHelper";
export default function GoogleAnalytics() {
const pathname = usePathname();
const searchParams = useSearchParams();
const GA_MEASUREMENT_ID = `${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`;
useEffect(() => {
const url = pathname + searchParams.toString();
pageview(GA_MEASUREMENT_ID, url);
}, [pathname, searchParams, GA_MEASUREMENT_ID]);
return (
<>
<Script
async
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
/>
<Script
async
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': 'granted'
});
gtag('config', '${GA_MEASUREMENT_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
);
}
字符串
//页面视图
export const pageview = (GA_MEASUREMENT_ID: string, url: string) => {
window.gtag("config", GA_MEASUREMENT_ID, {
page_path: url,
});
};
型
1条答案
按热度按时间a14dhokn1#
您可以使用Metadata Nextjs组件将所有元数据标记作为对象从布局页面导出元数据。
字符串
这将覆盖NextJS服务器默认生成的Meta标记,并有很多其他自定义。