|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { useEffect } from 'react' |
| 4 | +import Script from 'next/script' |
| 5 | + |
| 6 | +import type { FBPixelProps } from '../types/meta' |
| 7 | + |
| 8 | +export const FacebookPixel = (props: FBPixelProps) => { |
| 9 | + const { |
| 10 | + pixelId, |
| 11 | + pixelScriptUrl = 'https://connect.facebook.net/en_US/fbevents.js', |
| 12 | + } = props |
| 13 | + |
| 14 | + useEffect(() => { |
| 15 | + // performance.mark is being used as a feature use signal. While it is traditionally used for performance |
| 16 | + // benchmarking it is low overhead and thus considered safe to use in production and it is a widely available |
| 17 | + // existing API. |
| 18 | + // The performance measurement will be handled by Chrome Aurora |
| 19 | + |
| 20 | + performance.mark('mark_feature_usage', { |
| 21 | + detail: { |
| 22 | + feature: 'next-third-parties-fb-pixel', |
| 23 | + }, |
| 24 | + }) |
| 25 | + }, []) |
| 26 | + |
| 27 | + return ( |
| 28 | + <> |
| 29 | + <Script |
| 30 | + id="_next-fb-pixel" |
| 31 | + strategy="afterInteractive" |
| 32 | + dangerouslySetInnerHTML={{ |
| 33 | + _html: ` |
| 34 | + !function(f,b,e,v,n,t,s) |
| 35 | + {if(f.fbq)return;n=f.fbq=function(){n.callMethod? |
| 36 | + n.callMethod.apply(n,arguments):n.queue.push(arguments)}; |
| 37 | + if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0'; |
| 38 | + n.queue=[];t=b.createElement(e);t.async=!0; |
| 39 | + t.src=v;s=b.getElementsByTagName(e)[0]; |
| 40 | + s.parentNode.insertBefore(t,s)}(window, document,'script', |
| 41 | + '${pixelScriptUrl}'); |
| 42 | + fbq('init', '${pixelId}'); |
| 43 | + fbq('track', 'PageView'); |
| 44 | + `, |
| 45 | + }} |
| 46 | + /> |
| 47 | + <noscript> |
| 48 | + <img |
| 49 | + height="1" |
| 50 | + width="1" |
| 51 | + style={{ display: 'none' }} |
| 52 | + src={`https://www.facebook.com/tr?id=${pixelId}&ev=PageView&noscript=1`} |
| 53 | + /> |
| 54 | + </noscript> |
| 55 | + </> |
| 56 | + ) |
| 57 | +} |
| 58 | + |
| 59 | +// https://developers.facebook.com/docs/facebook-pixel/advanced/ |
| 60 | +export const pageView = () => { |
| 61 | + window?.fbq('track', 'PageView') |
| 62 | +} |
| 63 | + |
| 64 | +export const trackPixelEvent = (name: string, options: any = {}) => { |
| 65 | + window?.fbq('track', name, options) |
| 66 | +} |
0 commit comments