|
| 1 | +const initClientConversionTracking = () => { |
| 2 | + console.debug('Running initClientConversionTracking'); |
| 3 | + |
| 4 | + const { a: API_HOST, k: PUBLISHABLE_KEY } = window._dubAnalytics; |
| 5 | + |
| 6 | + console.log({ |
| 7 | + API_HOST, |
| 8 | + PUBLISHABLE_KEY, |
| 9 | + }); |
| 10 | + |
| 11 | + // Track lead conversion |
| 12 | + const trackLead = async (input) => { |
| 13 | + console.debug('Calling trackLead', input); |
| 14 | + |
| 15 | + const response = await fetch(`${API_HOST}/track/lead/client`, { |
| 16 | + method: 'POST', |
| 17 | + headers: { |
| 18 | + 'Content-Type': 'application/json', |
| 19 | + Authorization: `Bearer ${PUBLISHABLE_KEY}`, |
| 20 | + }, |
| 21 | + body: JSON.stringify(input), |
| 22 | + }); |
| 23 | + |
| 24 | + const result = await response.json(); |
| 25 | + |
| 26 | + if (!response.ok) { |
| 27 | + console.error('[dubAnalytics] trackLead failed', result.error); |
| 28 | + } |
| 29 | + |
| 30 | + return result; |
| 31 | + }; |
| 32 | + |
| 33 | + // Track sale conversion |
| 34 | + const trackSale = async (input) => { |
| 35 | + console.debug('Calling trackSale', input); |
| 36 | + |
| 37 | + const response = await fetch(`${API_HOST}/track/sale/client`, { |
| 38 | + method: 'POST', |
| 39 | + headers: { |
| 40 | + 'Content-Type': 'application/json', |
| 41 | + Authorization: `Bearer ${PUBLISHABLE_KEY}`, |
| 42 | + }, |
| 43 | + body: JSON.stringify(input), |
| 44 | + }); |
| 45 | + |
| 46 | + const result = await response.json(); |
| 47 | + |
| 48 | + if (!response.ok) { |
| 49 | + console.error('[dubAnalytics] trackSale failed', result.error); |
| 50 | + } |
| 51 | + |
| 52 | + return result; |
| 53 | + }; |
| 54 | + |
| 55 | + // Process the queued events |
| 56 | + if (window.dubAnalytics) { |
| 57 | + const original = window.dubAnalytics; |
| 58 | + const queue = original.q || []; |
| 59 | + |
| 60 | + // Create a callable function |
| 61 | + // Eg: dubAnalytics('trackLead', {}); |
| 62 | + function dubAnalytics(method, ...args) { |
| 63 | + if (method === 'trackLead') { |
| 64 | + trackLead(...args); |
| 65 | + } else if (method === 'trackSale') { |
| 66 | + trackSale(...args); |
| 67 | + } else { |
| 68 | + console.warn('[dubAnalytics] Unknown method:', method); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + dubAnalytics.q = queue; |
| 73 | + |
| 74 | + dubAnalytics.trackLead = function (...args) { |
| 75 | + trackLead(...args); |
| 76 | + }; |
| 77 | + |
| 78 | + dubAnalytics.trackSale = function (...args) { |
| 79 | + trackSale(...args); |
| 80 | + }; |
| 81 | + |
| 82 | + window.dubAnalytics = { |
| 83 | + ...original, |
| 84 | + ...dubAnalytics, |
| 85 | + }; |
| 86 | + } |
| 87 | +}; |
| 88 | + |
| 89 | +// Run when base script is ready |
| 90 | +if (window._dubAnalytics) { |
| 91 | + initClientConversionTracking(); |
| 92 | +} else { |
| 93 | + window.addEventListener('load', initClientConversionTracking); |
| 94 | +} |
0 commit comments