fix metrics

This commit is contained in:
Sergey Krylov 2025-03-26 11:53:40 +03:00
parent 150f44c918
commit cd22f97992
3 changed files with 38 additions and 45 deletions

View File

@ -1,7 +1,7 @@
import YandexMetrikaContainer from '@/components/metrika';
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css"; import "./globals.css";
import YandexMetrika from '@/components/metrika';
const geistSans = Geist({ const geistSans = Geist({
variable: "--font-geist-sans", variable: "--font-geist-sans",
@ -25,7 +25,6 @@ export const metadata: Metadata = {
} }
}; };
const analyticsEnabled = (process.env.NODE_ENV === "production");
export default function RootLayout({ export default function RootLayout({
children, children,
@ -39,7 +38,7 @@ export default function RootLayout({
> >
{children} {children}
<YandexMetrikaContainer enabled={analyticsEnabled} /> <YandexMetrika id="100593564" />
</body> </body>
</html> </html>
); );

View File

@ -1,47 +1,41 @@
"use client"; /* eslint-disable @next/next/no-img-element */
import Script from 'next/script'
import Router from "next/router"; const YandexMetrika = ({ id }: { id: string }) => (
import React, { useCallback, useEffect } from "react"; <>
import ym, { YMInitializer } from "react-yandex-metrika"; <Script
id='yandex-metrika'
strategy='afterInteractive'
dangerouslySetInnerHTML={{
__html: `
(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", "ym");
type Props = { ym(${id}, "init", {
enabled: boolean; clickmap:true,
}; trackLinks:true,
accurateTrackBounce:true,
const YM_COUNTER_ID = 100593564; webvisor:true
});
const YandexMetrikaContainer: React.FC<Props> = ({ enabled }) => { `,
const hit = useCallback(
(url: string) => {
if (enabled) {
ym("hit", url);
} else {
console.log(`%c[YandexMetrika](HIT)`, `color: orange`, url);
}
},
[enabled],
);
useEffect(() => {
hit(window.location.pathname + window.location.search);
Router.events.on("routeChangeComplete", (url: string) => hit(url));
}, [hit]);
if (!enabled) return null;
return (
<YMInitializer
accounts={[YM_COUNTER_ID]}
options={{
defer: true,
webvisor: true,
clickmap: true,
trackLinks: true,
accurateTrackBounce: true,
}} }}
version="2"
/> />
); <noscript>
}; <div>
<img
src={`https://mc.yandex.ru/watch/${id}`}
style={{ position: 'absolute', left: '-9999px' }}
alt=''
/>
</div>
</noscript>
</>
)
export default YandexMetrikaContainer; export default YandexMetrika