UNPKG

next-facebook-tracking

Version:

A simple package to help you integrate Facebook Pixel and Conversions API with Next.js

2 lines (1 loc) 1.01 kB
"use client";import{jsx as s,jsxs as b}from"react/jsx-runtime";import r from"next/script.js";import{createContext as l,useContext as c,useState as d}from"react";const t=l(null),g=({children:o,pixelId:e,debug:n})=>{const[a,i]=d(!1);return b(t.Provider,{value:{loaded:a,debug:n},children:[o,e?s(r,{id:"fb-pixel",src:"/scripts/pixel.js",strategy:"afterInteractive",onLoad:()=>i(!0),"data-pixel-id":e}):null]})};function k(){const o=c(t);if(o===null)throw new Error("useFacebookPixel must be used within a FacebookTrackingProvider");return o.loaded?{track(e){o.debug&&console.log("Facebook Pixel: ",e),window.fbq("track",e.event_name,e.custom_data,{eventID:e.event_id})},grantConsent(){o.debug&&console.log("Facebook Pixel: Consent granted"),window.fbq("consent","grant")},revokeConsent(){o.debug&&console.log("Facebook Pixel: Consent revoked"),window.fbq("consent","revoke")},init(e){o.debug&&console.log("Facebook Pixel: Init",e),window.fbq("init",e)}}:null}export{g as FacebookPixelProvider,k as useFacebookPixel};