yandex和google统计修改
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import Script from "next/script";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
/** Google Analytics 4 */
|
||||
const GA_ID = "G-5XKDE5QPTF";
|
||||
/** Yandex.Metrika 计数器 */
|
||||
const YM_ID = 113808100;
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ym?: (id: number, action: string, ...args: unknown[]) => void;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 站点统计:GA4 + Yandex.Metrika。
|
||||
* GA4 增强型衡量会按浏览器历史变化自动记录浏览量;
|
||||
* Metrika 在客户端路由切换时需手动发送 hit(首屏由 init 统计,不重复发)。
|
||||
*/
|
||||
export function SiteAnalytics() {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const lastUrl = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const query = searchParams.toString();
|
||||
const url = `${pathname}${query ? `?${query}` : ""}`;
|
||||
if (lastUrl.current === null) {
|
||||
lastUrl.current = url;
|
||||
return;
|
||||
}
|
||||
if (lastUrl.current === url) return;
|
||||
const referer = new URL(lastUrl.current, location.origin).href;
|
||||
lastUrl.current = url;
|
||||
window.ym?.(YM_ID, "hit", location.href, { referer, title: document.title });
|
||||
}, [pathname, searchParams]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Script src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} strategy="afterInteractive" />
|
||||
<Script id="ga4" strategy="afterInteractive">
|
||||
{`window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', '${GA_ID}');`}
|
||||
</Script>
|
||||
<Script id="yandex-metrika" strategy="afterInteractive">
|
||||
{`(function(m,e,t,r,i,k,a){
|
||||
m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
|
||||
m[i].l=1*new Date();
|
||||
for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
|
||||
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)
|
||||
})(window, document,'script','https://mc.yandex.ru/metrika/tag.js?id=${YM_ID}', 'ym');
|
||||
ym(${YM_ID}, 'init', {ssr:true, webvisor:true, clickmap:true, ecommerce:"dataLayer", referrer: document.referrer, url: location.href, accurateTrackBounce:true, trackLinks:true});`}
|
||||
</Script>
|
||||
<noscript>
|
||||
<div>
|
||||
<img src={`https://mc.yandex.ru/watch/${YM_ID}`} style={{ position: "absolute", left: "-9999px" }} alt="" />
|
||||
</div>
|
||||
</noscript>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user