fix externalId

This commit is contained in:
dev.daminik00 2025-12-24 14:44:30 +03:00
parent a75ac7e8c8
commit 408429d2e9

View File

@ -1,6 +1,7 @@
"use client";
import Script from "next/script";
import { useEffect, useMemo, useRef } from "react";
interface AnalyticsData {
facebook_pixel?: string[];
@ -13,6 +14,13 @@ interface AnalyticsScriptsProps {
externalId?: string; // visitorId from fingerprint - used for matching across Pixel and CAPI
}
// Declare fbq for TypeScript
declare global {
interface Window {
fbq?: (...args: unknown[]) => void;
}
}
/**
* Компонент для инъекции аналитических скриптов через next/script
*
@ -25,19 +33,45 @@ interface AnalyticsScriptsProps {
* - Лучшая производительность через оптимизации Next.js
*/
export function AnalyticsScripts({ data, externalId }: AnalyticsScriptsProps) {
const facebookPixels = useMemo(() => data?.facebook_pixel || [], [data?.facebook_pixel]);
const googleAnalyticsIds = data?.google_analytics || [];
const yandexMetrikaIds = data?.yandex_metrica || [];
// Track which pixels have been initialized with external_id
const initializedPixelsRef = useRef<Set<string>>(new Set());
// Initialize FB Pixel when externalId becomes available
useEffect(() => {
if (!externalId || facebookPixels.length === 0) return;
// Wait for fbq to be available
const initPixels = () => {
if (!window.fbq) {
// SDK not loaded yet, retry in 100ms
setTimeout(initPixels, 100);
return;
}
facebookPixels.forEach((pixelId) => {
if (initializedPixelsRef.current.has(pixelId)) return;
window.fbq!("init", pixelId, { external_id: externalId });
window.fbq!("track", "PageView");
initializedPixelsRef.current.add(pixelId);
});
};
initPixels();
}, [externalId, facebookPixels]);
if (!data) return null;
const facebookPixels = data.facebook_pixel || [];
const googleAnalyticsIds = data.google_analytics || [];
const yandexMetrikaIds = data.yandex_metrica || [];
return (
<>
{/* Facebook Pixel Scripts */}
{facebookPixels.map((pixelId) => (
{/* Facebook Pixel SDK - loads immediately, init happens in useEffect when externalId ready */}
{facebookPixels.length > 0 && (
<Script
key={`fb-pixel-${pixelId}`}
id={`fb-pixel-${pixelId}`}
id="fb-pixel-sdk"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
@ -49,12 +83,10 @@ n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '${pixelId}'${externalId ? `, { external_id: '${externalId}' }` : ''});
fbq('track', 'PageView');
`.trim(),
}}
/>
))}
)}
{/* Google Analytics Scripts */}
{googleAnalyticsIds.map((measurementId) => (