53 lines
1.1 KiB
TypeScript
53 lines
1.1 KiB
TypeScript
import {META_PIXEL_ID} from '~/lib/metaPixel';
|
|
|
|
declare global {
|
|
interface Window {
|
|
fbq?: FbqFunction;
|
|
_fbq?: FbqFunction;
|
|
}
|
|
}
|
|
|
|
type FbqFunction = {
|
|
(...args: unknown[]): void;
|
|
callMethod?: (...args: unknown[]) => void;
|
|
queue: unknown[][];
|
|
push: FbqFunction;
|
|
loaded?: boolean;
|
|
version?: string;
|
|
};
|
|
|
|
/** Load Meta Pixel after hydration (avoids mutating `<head>` during React hydrate). */
|
|
export function loadMetaPixel(): void {
|
|
if (typeof window === 'undefined') return;
|
|
if (typeof window.fbq === 'function') return;
|
|
|
|
const f = window;
|
|
const b = document;
|
|
const e = 'script';
|
|
const v = 'https://connect.facebook.net/en_US/fbevents.js';
|
|
|
|
const n = function (...args: unknown[]) {
|
|
if (n.callMethod) {
|
|
n.callMethod(...args);
|
|
} else {
|
|
n.queue.push(args);
|
|
}
|
|
} as FbqFunction;
|
|
|
|
if (!f._fbq) f._fbq = n;
|
|
n.push = n;
|
|
n.loaded = true;
|
|
n.version = '2.0';
|
|
n.queue = [];
|
|
f.fbq = n;
|
|
|
|
const t = b.createElement(e) as HTMLScriptElement;
|
|
t.async = true;
|
|
t.src = v;
|
|
const s = b.getElementsByTagName(e)[0];
|
|
s?.parentNode?.insertBefore(t, s);
|
|
|
|
f.fbq('init', META_PIXEL_ID);
|
|
f.fbq('track', 'PageView');
|
|
}
|