separate meta init from PixelControl.for

This commit is contained in:
Elijah Duffy
2025-12-16 17:55:18 -08:00
parent 04ce2d3c57
commit ae08a564a8

View File

@@ -57,17 +57,22 @@
* Returns a PixelControl instance for the given Meta Pixel ID. If * Returns a PixelControl instance for the given Meta Pixel ID. If
* the base Meta Pixel script has not been loaded yet, it will be * the base Meta Pixel script has not been loaded yet, it will be
* loaded automatically. Optionally sets a test event code for the Pixel. * loaded automatically. Optionally sets a test event code for the Pixel.
* Does NOT initialize the Pixel; call `fireInit()` on the returned instance
* before tracking events.
* @param trackingManager Tracking manager to handle user consent for tracking
* @param pixelID Meta Pixel ID * @param pixelID Meta Pixel ID
* @param testEventCode Optional test event code * @param options Optional settings
* @returns PixelControl instance * @returns PixelControl instance
*/ */
static for( static for(
trackingManager: MaybeGetter<TrackingManager | undefined>, trackingManager: MaybeGetter<TrackingManager | undefined>,
pixelID: string, pixelID: string,
options?: { options?: {
/**
* if provided, events fired will always have this code attached
* to prevent them from polluting real analytics data.
*/
testEventCode?: string; testEventCode?: string;
advancedMatching?: AdvancedMatching;
initOptions?: InitOptions;
} }
): PixelControl { ): PixelControl {
PixelControl.load(); PixelControl.load();
@@ -75,6 +80,19 @@
return new PixelControl(trackingManager, pixelID, options?.testEventCode); return new PixelControl(trackingManager, pixelID, options?.testEventCode);
} }
/**
* Initializes this pixel with the Meta Pixel API including any advanced
* matching data and options.
* @param advancedMatching Advanced matching data
* @param initOptions Initialization options
* @returns this PixelControl instance
*/
fireInit(advancedMatching?: AdvancedMatching, initOptions?: InitOptions): PixelControl {
PixelControl.loadGuard();
window.fbq('init', this._pixelID, advancedMatching, initOptions);
return this;
}
/** /**
* Checks if the Meta Pixel has consent to track user data * Checks if the Meta Pixel has consent to track user data
* and if the Pixel has been loaded. * and if the Pixel has been loaded.
@@ -171,7 +189,7 @@
throw new Error('MetaPixel component requires a TrackingManager to manage consent.'); throw new Error('MetaPixel component requires a TrackingManager to manage consent.');
} }
PixelControl.load(); PixelControl.load();
pixel = PixelControl.for(trackingManager, pixelID, { testEventCode }); pixel = PixelControl.for(trackingManager, pixelID, { testEventCode }).fireInit();
trackingManager.runWithConsent(() => { trackingManager.runWithConsent(() => {
if (autoPageView && pixel) { if (autoPageView && pixel) {