-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbrowser.js
More file actions
333 lines (305 loc) · 11.3 KB
/
Copy pathbrowser.js
File metadata and controls
333 lines (305 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/* eslint-disable func-names */
/* eslint-disable prefer-rest-params */
/* eslint-disable prefer-spread */
/* eslint-disable no-underscore-dangle */
/* eslint-disable class-methods-use-this */
import each from '@ndhoule/each';
import sha256 from 'crypto-js/sha256';
import { ScriptLoader } from '@rudderstack/analytics-js-legacy-utilities/ScriptLoader';
import { NAME, traitsMapper, reserveTraits, DISPLAY_NAME } from './constants';
import Logger from '../../utils/logger';
import {
merge,
getEventId,
buildPayLoad,
getHashedStatus,
eventHelpers,
formatRevenue,
getContentType,
getContentCategory,
getProductContentAndId,
getProductListViewedEventParams,
getProductsContentsAndContentIds,
} from './utils';
import { getHashFromArray } from '../../utils/commonUtils';
import { constructPayload } from '../../utils/utils';
const logger = new Logger(DISPLAY_NAME);
class FacebookPixel {
constructor(config, analytics, destinationInfo) {
if (analytics.logLevel) {
logger.setLogLevel(analytics.logLevel);
}
this.autoConfig = config.autoConfig === undefined ? true : config.autoConfig;
this.blacklistPiiProperties = config.blacklistPiiProperties;
this.categoryToContent = config.categoryToContent || [];
this.pixelId = config.pixelId;
this.eventsToEvents = config.eventsToEvents;
this.valueFieldIdentifier = config.valueFieldIdentifier;
this.advancedMapping = config.advancedMapping;
this.traitKeyToExternalId = config.traitKeyToExternalId;
this.legacyConversionPixelId = config.legacyConversionPixelId || [];
this.userIdAsPixelId = config.userIdAsPixelId || [];
this.whitelistPiiProperties = config.whitelistPiiProperties;
this.useUpdatedMapping = config.useUpdatedMapping;
this.name = NAME;
this.analytics = analytics;
({
shouldApplyDeviceModeTransformation: this.shouldApplyDeviceModeTransformation,
propagateEventsUntransformedOnError: this.propagateEventsUntransformedOnError,
destinationId: this.destinationId,
} = destinationInfo ?? {});
}
init() {
// Bootstrap the global fbq shim only once per page. When multiple Meta Pixel
// destinations are configured, each one calls init(), and re-running this block
// mutates the already loaded fbevents.js SDK (resetting fbq.version, fbq.queue, etc.),
// which makes Meta log "Multiple pixels with conflicting versions were detected"
// and prevents the second pixel from initializing. Guard it like Meta's own snippet.
if (!window.fbq) {
window._fbq = function () {
if (window.fbq.callMethod) {
window.fbq.callMethod.apply(window.fbq, arguments);
} else {
window.fbq.queue.push(arguments);
}
};
window.fbq = window.fbq || window._fbq;
window.fbq.push = window.fbq;
window.fbq.loaded = true;
window.fbq.version = '2.0';
window.fbq.queue = [];
}
// Apply these flags on every init() (even when fbq was bootstrapped by the host page
// or an earlier destination), so we never fall back to Meta's automatic pageview
// tracking. They don't cause the version conflict, so they stay outside the guard.
window.fbq.disablePushState = true; // disables automatic pageview tracking
window.fbq.allowDuplicatePageViews = true; // enables fb
window.fbq('set', 'autoConfig', this.autoConfig, this.pixelId); // toggle autoConfig : sends button click and page metadata
if (this.advancedMapping) {
if (this.useUpdatedMapping) {
const userData = {
context: {
traits: { ...this.analytics.getUserTraits() },
},
userId: this.analytics.getUserId(),
anonymousId: this.analytics.getAnonymousId(),
};
const userPayload = constructPayload(userData, traitsMapper);
// here we are sending other traits apart from the reserved ones.
reserveTraits.forEach(element => {
delete userData.context?.traits[element];
});
this.userPayload = { ...userPayload, ...userData.context.traits };
if (this.userPayload.external_id) {
this.userPayload.external_id = sha256(this.userPayload.external_id).toString();
}
} else {
this.userPayload = { ...this.analytics.getUserTraits() };
}
window.fbq('init', this.pixelId, this.userPayload);
} else {
window.fbq('init', this.pixelId);
}
ScriptLoader('fbpixel-integration', 'https://connect.facebook.net/en_US/fbevents.js');
}
isLoaded() {
return !!window.fbq?.callMethod;
}
isReady() {
return this.isLoaded();
}
page(rudderElement) {
const { properties } = rudderElement.message;
window.fbq('track', 'PageView', properties, {
eventID: getEventId(rudderElement.message),
});
}
track(rudderElement) {
const { event } = rudderElement.message;
const properties = eventHelpers.getProperties(rudderElement.message);
const {
id,
sku,
name,
price,
query,
revenue,
products,
quantity,
contentName,
product_id: productId,
product_name: productName,
delivery_category: deliveryCategory,
content_type: contentType,
} = properties;
let { value, category, currency } = properties;
const revValue = formatRevenue(revenue);
eventHelpers.validateRevenue(revValue);
currency = eventHelpers.getCurrency(currency);
const payload = buildPayLoad(
rudderElement,
this.whitelistPiiProperties,
this.blacklistPiiProperties,
getHashedStatus(rudderElement.message),
);
const standard = this.eventsToEvents;
const legacy = this.legacyConversionPixelId;
const standardTo = getHashFromArray(standard);
const legacyTo = getHashFromArray(legacy);
const useValue = this.valueFieldIdentifier === 'properties.value';
const prodId = eventHelpers.getProdId(productId, sku, id);
value = eventHelpers.getFormattedRevenue(revValue, value);
// check for category data type
if (category && !getContentCategory(category)) {
return;
}
category = getContentCategory(category);
const derivedEventID = getEventId(rudderElement.message);
if (event === 'Product List Viewed') {
const {
contentIds,
contentType: defaultContentType,
contents,
} = getProductListViewedEventParams(properties);
const productInfo = {
content_ids: contentIds,
content_type:
contentType || getContentType(rudderElement, defaultContentType, this.categoryToContent),
contents,
content_category: eventHelpers.getCategory(category),
content_name: contentName,
value,
currency,
};
this.makeTrackSignalCall(
this.pixelId,
'ViewContent',
merge(productInfo, payload),
derivedEventID,
);
this.makeTrackSignalCalls(this.pixelId, event, legacyTo, derivedEventID, {
currency,
value: revValue,
});
} else if (event === 'Product Viewed' || event === 'Product Added') {
const { contents, contentIds } = getProductContentAndId(prodId, quantity, price);
const productInfo = {
content_ids: contentIds,
content_type:
contentType || getContentType(rudderElement, 'product', this.categoryToContent),
content_name: eventHelpers.getProdName(productName, name),
content_category: eventHelpers.getCategory(category),
currency,
value: eventHelpers.getValue(useValue, value, price),
contents,
};
this.makeTrackSignalCall(
this.pixelId,
eventHelpers.getEventName(event),
merge(productInfo, payload),
derivedEventID,
);
this.makeTrackSignalCalls(this.pixelId, event, legacyTo, derivedEventID, {
currency,
value: productInfo.value,
});
} else if (event === 'Order Completed') {
const { contents, contentIds } = getProductsContentsAndContentIds(
products,
quantity,
price,
deliveryCategory,
);
// ref: https://developers.facebook.com/docs/meta-pixel/implementation/marketing-api#purchase
// "trackSingle" feature is :
// https://developers.facebook.com/ads/blog/post/v2/2017/11/28/event-tracking-with-multiple-pixels-tracksingle/
const productInfo = {
content_ids: contentIds,
content_type:
contentType || getContentType(rudderElement, 'product', this.categoryToContent),
currency,
value: revValue,
contents,
num_items: contentIds.length,
content_name: contentName,
};
this.makeTrackSignalCall(
this.pixelId,
'Purchase',
merge(productInfo, payload),
derivedEventID,
);
this.makeTrackSignalCalls(this.pixelId, event, legacyTo, derivedEventID, {
currency,
value: revValue,
});
} else if (event === 'Products Searched') {
const { contents, contentIds } = getProductContentAndId(prodId, quantity, price);
const productInfo = {
content_ids: contentIds,
content_category: eventHelpers.getCategory(category),
currency,
value,
contents,
search_string: query,
};
this.makeTrackSignalCall(this.pixelId, 'Search', merge(productInfo, payload), derivedEventID);
this.makeTrackSignalCalls(this.pixelId, event, legacyTo, derivedEventID, { currency, value });
} else if (event === 'Checkout Started') {
let contentCategory = category;
const { contents, contentIds } = getProductsContentsAndContentIds(products, quantity, price);
if (Array.isArray(products) && !contentCategory && products[0]?.category) {
contentCategory = products[0].category;
}
const productInfo = {
content_ids: contentIds,
content_type:
contentType || getContentType(rudderElement, 'product', this.categoryToContent),
content_category: contentCategory,
currency,
value: revValue,
contents,
num_items: contentIds.length,
};
this.makeTrackSignalCall(
this.pixelId,
'InitiateCheckout',
merge(productInfo, payload),
derivedEventID,
);
this.makeTrackSignalCalls(this.pixelId, event, legacyTo, derivedEventID, {
currency,
value: revValue,
});
} else if (eventHelpers.isCustomEventNotMapped(standardTo, legacyTo, event)) {
payload.value = revValue;
window.fbq('trackSingleCustom', this.pixelId, event, payload, {
eventID: derivedEventID,
});
} else {
logger.info('Not standard event & no custom mapping available');
payload.value = revValue;
payload.currency = currency;
this.makeTrackSignalCalls(this.pixelId, event, standardTo, derivedEventID, payload);
this.makeTrackSignalCalls(this.pixelId, event, legacyTo, derivedEventID, {
currency,
value: revValue,
});
}
}
makeTrackSignalCalls(pixelId, event, array, derivedEventID, payload) {
each((val, key) => {
if (key === event.toLowerCase()) {
window.fbq('trackSingle', pixelId, val, payload, {
eventID: derivedEventID,
});
}
}, array);
}
makeTrackSignalCall(pixelId, event, payload, derivedEventID) {
window.fbq('trackSingle', pixelId, event, payload, {
eventID: derivedEventID,
});
}
}
export default FacebookPixel;