Skip to content

Commit 8de8767

Browse files
STRATCONN-5986 - [Facebook Pixel] - major refactor to fix advanced matching (#3514)
* major refactor to fix advanced matching * tidying up * fixing country and state dropdowns * testing and refactoring * saving progress * Claude happy * adding PageView * more work * more changes * more change * reorder presets * ready to deploy for testing * fiddling around with field mappings
1 parent 354c651 commit 8de8767

File tree

13 files changed

+542
-375
lines changed

13 files changed

+542
-375
lines changed

packages/browser-destinations/destinations/facebook-conversions-api-web/src/send/constants.ts renamed to packages/browser-destinations/destinations/facebook-conversions-api-web/src/constants.ts

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
export const MAX_INIT_COUNT = 2
2+
3+
export const INIT_COUNT_KEY = 'fb_pixel_init_count'
4+
5+
export const USER_DATA_KEY = 'fb_user_data'
6+
17
export const CURRENCY_ISO_CODES = new Set([
28
'AED',
39
'AFN',
@@ -280,11 +286,11 @@ export const COUNTRY_CODES = new Map<string, string>([
280286
['chile', 'cl'],
281287
['china', 'cn'],
282288
['christmasisland', 'cx'],
283-
['cocos(keeling)islands', 'cc'],
289+
['cocosislands', 'cc'],
284290
['colombia', 'co'],
285291
['comoros', 'km'],
286292
['congo', 'cg'],
287-
['congo,democraticrepublic', 'cd'],
293+
['congodemocraticrepublic', 'cd'],
288294
['cookislands', 'ck'],
289295
['costarica', 'cr'],
290296
["coted'ivoire", 'ci'],
@@ -303,7 +309,7 @@ export const COUNTRY_CODES = new Map<string, string>([
303309
['eritrea', 'er'],
304310
['estonia', 'ee'],
305311
['ethiopia', 'et'],
306-
['falklandislands(malvinas)', 'fk'],
312+
['falklandislands', 'fk'],
307313
['faroeislands', 'fo'],
308314
['fiji', 'fj'],
309315
['finland', 'fi'],
@@ -325,18 +331,16 @@ export const COUNTRY_CODES = new Map<string, string>([
325331
['guatemala', 'gt'],
326332
['guernsey', 'gg'],
327333
['guinea', 'gn'],
328-
['guinea-bissau', 'gw'],
334+
['guineabissau', 'gw'],
329335
['guyana', 'gy'],
330336
['haiti', 'ht'],
331-
['heardisland&mcdonaldislands', 'hm'],
332-
['holysee(vaticancitystate)', 'va'],
333337
['honduras', 'hn'],
334338
['hongkong', 'hk'],
335339
['hungary', 'hu'],
336340
['iceland', 'is'],
337341
['india', 'in'],
338342
['indonesia', 'id'],
339-
['iran,islamicrepublicof', 'ir'],
343+
['iran', 'ir'],
340344
['iraq', 'iq'],
341345
['ireland', 'ie'],
342346
['isleofman', 'im'],
@@ -352,12 +356,12 @@ export const COUNTRY_CODES = new Map<string, string>([
352356
['korea', 'kr'],
353357
['kuwait', 'kw'],
354358
['kyrgyzstan', 'kg'],
355-
["laopeople'sdemocraticrepublic", 'la'],
359+
['laos', 'la'],
356360
['latvia', 'lv'],
357361
['lebanon', 'lb'],
358362
['lesotho', 'ls'],
359363
['liberia', 'lr'],
360-
['libyanarabjamahiriya', 'ly'],
364+
['libya', 'ly'],
361365
['liechtenstein', 'li'],
362366
['lithuania', 'lt'],
363367
['luxembourg', 'lu'],
@@ -375,7 +379,7 @@ export const COUNTRY_CODES = new Map<string, string>([
375379
['mauritius', 'mu'],
376380
['mayotte', 'yt'],
377381
['mexico', 'mx'],
378-
['micronesia,federatedstatesof', 'fm'],
382+
['micronesia', 'fm'],
379383
['moldova', 'md'],
380384
['monaco', 'mc'],
381385
['mongolia', 'mn'],
@@ -401,7 +405,7 @@ export const COUNTRY_CODES = new Map<string, string>([
401405
['oman', 'om'],
402406
['pakistan', 'pk'],
403407
['palau', 'pw'],
404-
['palestinianterritory,occupied', 'ps'],
408+
['palestine', 'ps'],
405409
['panama', 'pa'],
406410
['papuanewguinea', 'pg'],
407411
['paraguay', 'py'],
@@ -414,6 +418,7 @@ export const COUNTRY_CODES = new Map<string, string>([
414418
['qatar', 'qa'],
415419
['reunion', 're'],
416420
['romania', 'ro'],
421+
['russia', 'ru'],
417422
['russianfederation', 'ru'],
418423
['rwanda', 'rw'],
419424
['saintbarthelemy', 'bl'],
@@ -437,7 +442,7 @@ export const COUNTRY_CODES = new Map<string, string>([
437442
['solomonislands', 'sb'],
438443
['somalia', 'so'],
439444
['southafrica', 'za'],
440-
['southgeorgiaandsandwichisl.', 'gs'],
445+
['southgeorgiaandsandwichislands', 'gs'],
441446
['spain', 'es'],
442447
['srilanka', 'lk'],
443448
['sudan', 'sd'],
@@ -446,12 +451,12 @@ export const COUNTRY_CODES = new Map<string, string>([
446451
['swaziland', 'sz'],
447452
['sweden', 'se'],
448453
['switzerland', 'ch'],
449-
['syrianarabrepublic', 'sy'],
454+
['syria', 'sy'],
450455
['taiwan', 'tw'],
451456
['tajikistan', 'tj'],
452457
['tanzania', 'tz'],
453458
['thailand', 'th'],
454-
['timor-leste', 'tl'],
459+
['timorleste', 'tl'],
455460
['togo', 'tg'],
456461
['tokelau', 'tk'],
457462
['tonga', 'to'],
@@ -465,15 +470,17 @@ export const COUNTRY_CODES = new Map<string, string>([
465470
['ukraine', 'ua'],
466471
['unitedarabemirates', 'ae'],
467472
['unitedkingdom', 'gb'],
473+
['greatbritain', 'gb'],
468474
['unitedstates', 'us'],
475+
['unitedstatesofamerica', 'us'],
469476
['unitedstatesoutlyingislands', 'um'],
470477
['uruguay', 'uy'],
471478
['uzbekistan', 'uz'],
472479
['vanuatu', 'vu'],
473480
['venezuela', 've'],
474481
['vietnam', 'vn'],
475-
['virginislands,british', 'vg'],
476-
['virginislands,u.s.', 'vi'],
482+
['virginislandsbritish', 'vg'],
483+
['virginislandsus', 'vi'],
477484
['wallisandfutuna', 'wf'],
478485
['westernsahara', 'eh'],
479486
['yemen', 'ye'],
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
import { WindowWithOptionalFbq, InitOptions, LDU, UserData, FBClient} from './types'
2+
import type { Settings } from './generated-types'
3+
import { USER_DATA_KEY, INIT_COUNT_KEY} from './constants'
4+
import { UniversalStorage, Analytics } from '@segment/analytics-next'
5+
6+
export function initScript(settings: Settings, analytics: Analytics) {
7+
const {
8+
pixelId,
9+
disablePushState,
10+
disableAutoConfig,
11+
disableFirstPartyCookies,
12+
agent,
13+
ldu
14+
} = settings as Settings & { ldu: keyof typeof LDU }
15+
16+
(function(
17+
f: WindowWithOptionalFbq,
18+
b: Document,
19+
e: 'script',
20+
v: string,
21+
n: FBClient | undefined = undefined,
22+
t: HTMLScriptElement | undefined = undefined,
23+
s: Element | null = null
24+
){
25+
if (f.fbq) return;
26+
n = f.fbq = function() {
27+
/* eslint-disable */
28+
// @ts-expect-error - n is defined by the time this executes
29+
n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
30+
/* eslint-enable */
31+
};
32+
if (!f._fbq) f._fbq = n;
33+
n.push = n;
34+
n.loaded = true;
35+
n.version = '2.0';
36+
n.queue = [];
37+
t = b.createElement(e);
38+
t.async = true;
39+
t.src = v;
40+
s = b.getElementsByTagName(e)[0];
41+
if (s && s.parentNode) {
42+
s.parentNode.insertBefore(t, s);
43+
}
44+
})(
45+
window,
46+
document,
47+
'script',
48+
'https://connect.facebook.net/en_US/fbevents.js'
49+
);
50+
51+
if(ldu === LDU.Disabled.key) {
52+
window.fbq('dataProcessingOptions', [])
53+
}
54+
else {
55+
const lduObj = getLDU(ldu)
56+
window.fbq('dataProcessingOptions', ['LDU'], lduObj.country, lduObj.state)
57+
}
58+
59+
if(disablePushState) {
60+
window.fbq.disablePushState = true
61+
}
62+
63+
if (disableAutoConfig) {
64+
window.fbq('set', 'autoConfig', false, pixelId)
65+
}
66+
67+
if (disableFirstPartyCookies) {
68+
window.fbq('set', 'firstPartyCookies', false, pixelId)
69+
}
70+
71+
const userData = getStoredUserData(analytics)
72+
const options: InitOptions | undefined = ( agent ? { agent } : undefined)
73+
const initArgs: [string, UserData?, InitOptions?] = [pixelId]
74+
75+
if (userData && Object.keys(userData).length > 0) {
76+
initArgs.push(userData);
77+
if (options) {
78+
initArgs.push(options);
79+
}
80+
} else if (options) {
81+
initArgs.push(undefined, options)
82+
}
83+
84+
window.fbq('init', ...initArgs)
85+
86+
setStorageInitCount(analytics, 1)
87+
deleteStorageUserData(analytics)
88+
89+
if(!disablePushState) {
90+
window.fbq('trackSingle', pixelId, 'PageView')
91+
}
92+
}
93+
94+
export const storageFallback = {
95+
get: (key: string) => {
96+
try {
97+
return window.localStorage.getItem(key)
98+
} catch {
99+
return null
100+
}
101+
},
102+
set: (key: string, value: string) => {
103+
try {
104+
window.localStorage.setItem(key, value)
105+
} catch {
106+
// Silently fail in private browsing
107+
}
108+
}
109+
}
110+
111+
export function setStorageInitCount(analytics: Analytics, count: number) {
112+
const storage = (analytics.storage as UniversalStorage<Record<string, string>>) ?? storageFallback
113+
storage.set(INIT_COUNT_KEY, `${count}`)
114+
}
115+
116+
export function deleteStorageUserData(analytics: Analytics) {
117+
const storage = (analytics.storage as UniversalStorage<Record<string, string>>) ?? storageFallback
118+
storage.set(USER_DATA_KEY, '')
119+
}
120+
121+
function getStoredUserData(analytics: Analytics): UserData | undefined {
122+
const storage = (analytics.storage as UniversalStorage<Record<string, string>>) ?? storageFallback
123+
const userDataFromStorage: string | null = storage.get(USER_DATA_KEY)
124+
if(userDataFromStorage) {
125+
try {
126+
const parsed = JSON.parse(userDataFromStorage)
127+
if(!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Object.keys(parsed as object).length === 0) {
128+
return undefined
129+
}
130+
return parsed as UserData
131+
} catch {
132+
return undefined
133+
}
134+
}
135+
return undefined
136+
}
137+
138+
function getLDU(ldu: keyof typeof LDU) {
139+
const lduObj = LDU[ldu]
140+
return { country: lduObj.country, state: lduObj.state }
141+
}

packages/browser-destinations/destinations/facebook-conversions-api-web/src/generated-types.ts

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)