UNPKG

@adkit.so/meta-pixel

Version:

Platform-agnostic Meta Pixel tracking wrapper with TypeScript support

157 lines (155 loc) 6.29 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; const logger = { info: (message, data) => { if (data !== void 0) { console.log(`%c[Meta Pixel]%c ${message}`, "background: #1877f2; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;", data); } else { console.log(`%c[Meta Pixel]%c ${message}`, "background: #1877f2; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;"); } }, warn: (message, data) => { if (data !== void 0) { console.warn(`%c[Meta Pixel]%c ${message}`, "background: #ff9800; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;", data); } else { console.warn(`%c[Meta Pixel]%c ${message}`, "background: #ff9800; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;"); } }, success: (message, data) => { if (data !== void 0) { console.log(`%c[Meta Pixel]%c ${message}`, "background: #4caf50; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;", data); } else { console.log(`%c[Meta Pixel]%c ${message}`, "background: #4caf50; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;"); } }, error: (message, data) => { if (data !== void 0) { console.error(`%c[Meta Pixel]%c ${message}`, "background: #f44336; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;", data); } else { console.error(`%c[Meta Pixel]%c ${message}`, "background: #f44336; color: white; font-weight: bold; padding: 2px 6px; border-radius: 3px;", "color: inherit;"); } } }; const STANDARD_EVENTS = ["PageView", "AddPaymentInfo", "AddToCart", "AddToWishlist", "CompleteRegistration", "Contact", "CustomizeProduct", "Donate", "FindLocation", "InitiateCheckout", "Lead", "Purchase", "Schedule", "Search", "StartTrial", "SubmitApplication", "Subscribe", "ViewContent"]; function isStandardEvent(event) { return STANDARD_EVENTS.includes(event); } class MetaPixel { constructor() { __publicField(this, "initialized", false); __publicField(this, "config", null); } /** * Initialize Meta Pixel with configuration */ init(config) { if (this.initialized) { logger.warn("Already initialized"); return; } this.config = { autoTrackPageView: true, debug: false, enableLocalhost: false, ...config }; if (typeof window === "undefined") { if (this.config.debug) logger.warn("Not in browser environment, skipping initialization"); return; } if (!this.config.enableLocalhost && window.location.hostname === "localhost") { if (this.config.debug) logger.info("Disabled on localhost (set enableLocalhost: true to enable for testing)"); return; } const pixelIds = Array.isArray(config.pixelIds) ? config.pixelIds : [config.pixelIds]; if (!pixelIds.length || pixelIds.every((id) => !id)) { logger.warn("No pixel IDs provided"); return; } if (this.config.debug) logger.info("Initializing Meta Pixel...", { pixelIds, autoTrackPageView: this.config.autoTrackPageView }); this.loadScript(pixelIds); this.initialized = true; if (this.config.debug) logger.success("\u2713 Meta Pixel initialized successfully"); } /** * Load the Facebook Pixel script */ loadScript(pixelIds) { const script = document.createElement("script"); script.async = true; script.defer = true; const pixelCode = pixelIds.filter((id) => id).map((id) => `fbq('init', '${id}');`).join("\n"); const autoPageView = this.config?.autoTrackPageView ? `fbq('track', 'PageView');` : ""; script.innerHTML = ` !(function (f, b, e, v, n, t, s) { if (f.fbq) return; n = f.fbq = function () { n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments); }; if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0'; 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'); ${pixelCode} ${autoPageView} `; document.head.appendChild(script); } /** * Track a standard event (use trackCustom for custom events) */ track(event, data = {}, eventData = {}) { if (!this.isLoaded()) { logger.warn(`Event "${event}" not tracked - Pixel not loaded`); return; } if (isStandardEvent(event)) { if (this.config?.debug) logger.info(`Tracking standard event: "${event}"`, { data, eventData }); window.fbq("track", event, data, eventData); } else { logger.warn(`"${event}" is not a standard event. Use trackCustom() instead for custom events.`); if (this.config?.debug) logger.info(`Tracking custom event: "${event}"`, { data, eventData }); window.fbq("trackCustom", event, data, eventData); } } /** * Track a custom event */ trackCustom(event, data = {}, eventData = {}) { if (!this.isLoaded()) { logger.warn(`Custom event "${event}" not tracked - Pixel not loaded`); return; } if (this.config?.debug) logger.info(`Tracking custom event: "${event}"`, { data, eventData }); window.fbq("trackCustom", event, data, eventData); } /** * Check if Meta Pixel is loaded */ isLoaded() { return typeof window !== "undefined" && typeof window.fbq === "function"; } } const META = new MetaPixel(); function createMetaPixel() { return new MetaPixel(); } export { META, createMetaPixel, META as default };