-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapache-unomi-tracker.js
More file actions
1509 lines (1386 loc) · 68.7 KB
/
apache-unomi-tracker.js
File metadata and controls
1509 lines (1386 loc) · 68.7 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @ts-expect-error This module is typed starting v4, we are using v3
import { Crawler } from 'es6-crawler-detect';
/** @import { AjaxOptions, DigitalData, UnomiEvent, Personalization, PersonalizationCallback, Variant, UnomiObject, UnomiProperties } from "./types" */
export const useTracker = () => {
const wem = {
digitalData: /** @type {DigitalData} */(/** @type {unknown} */(undefined)),
trackerProfileIdCookieName: 'wem-profile-id',
trackerSessionIdCookieName: 'wem-session-id',
browserGeneratedSessionSuffix: '',
disableTrackedConditionsListeners: false,
activateWem: true,
contextServerCookieName: 'context-profile-id',
contextServerUrl: '',
timeoutInMilliseconds: 1500,
formNamesToWatch: /** @type {string[]} */([]),
eventsPrevented: /** @type {string[]} */([]),
/** @type {string | null} */
sessionID: null,
fallback: false,
/** @type {any} */
cxs: undefined,
DOMLoaded: false,
/** @type {string | undefined} */
contextLoaded: undefined,
/**
* This function initialize the tracker
*
* @param {DigitalData} digitalData config of the tracker
* @returns {undefined}
*/
initTracker: function (digitalData) {
wem.digitalData = digitalData;
wem.trackerProfileIdCookieName = wem.digitalData.wemInitConfig.trackerProfileIdCookieName ? wem.digitalData.wemInitConfig.trackerProfileIdCookieName : 'wem-profile-id';
wem.trackerSessionIdCookieName = wem.digitalData.wemInitConfig.trackerSessionIdCookieName ? wem.digitalData.wemInitConfig.trackerSessionIdCookieName : 'wem-session-id';
wem.browserGeneratedSessionSuffix = wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix ? wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix : '';
wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners || false;
wem.activateWem = wem.digitalData.wemInitConfig.activateWem;
const { contextServerUrl, timeoutInMilliseconds, contextServerCookieName } = wem.digitalData.wemInitConfig;
wem.contextServerCookieName = contextServerCookieName;
wem.contextServerUrl = contextServerUrl;
wem.timeoutInMilliseconds = timeoutInMilliseconds;
wem.formNamesToWatch = [];
wem.eventsPrevented = [];
wem.sessionID = wem.getCookie(wem.trackerSessionIdCookieName);
wem.fallback = false;
if (wem.sessionID === null) {
console.warn('[WEM] sessionID is null !');
} else if (!wem.sessionID || wem.sessionID === '') {
console.warn('[WEM] empty sessionID, setting to null !');
wem.sessionID = null;
}
},
/**
* This function start the tracker by loading the context in the page
* Note: that the tracker will start once the current DOM is complete loaded, using listener on current document: DOMContentLoaded
*
* @param {Array<Partial<DigitalData>>} [digitalDataOverrides] optional, list of digitalData extensions, they will be merged with original digitalData before context loading
* @returns {undefined}
*/
startTracker: function (digitalDataOverrides = undefined) {
// Check before start
let cookieDisabled = !navigator.cookieEnabled;
let noSessionID = !wem.sessionID || wem.sessionID === '';
let crawlerDetected = navigator.userAgent;
if (crawlerDetected) {
const browserDetector = new Crawler();
crawlerDetected = browserDetector.isCrawler(navigator.userAgent);
}
if (cookieDisabled || noSessionID || crawlerDetected) {
document.addEventListener('DOMContentLoaded', function () {
wem._executeFallback('navigator cookie disabled: ' + cookieDisabled + ', no sessionID: ' + noSessionID + ', web crawler detected: ' + crawlerDetected);
});
return;
}
// Register base context callback
wem._registerCallback(function () {
if (wem.cxs.profileId) {
wem.setCookie(wem.trackerProfileIdCookieName, wem.cxs.profileId);
}
if (!wem.cxs.profileId) {
wem.removeCookie(wem.trackerProfileIdCookieName);
}
if (!wem.disableTrackedConditionsListeners) {
wem._registerListenersForTrackedConditions();
}
}, 'Default tracker', 0);
// Load the context once document is ready
document.addEventListener('DOMContentLoaded', function () {
wem.DOMLoaded = true;
// enrich digital data considering extensions
wem._handleDigitalDataOverrides(digitalDataOverrides);
// complete already registered events
wem._checkUncompleteRegisteredEvents();
// Dispatch javascript events for the experience (perso/opti displayed from SSR, based on unomi events)
wem._dispatchJSExperienceDisplayedEvents();
// Some event may not need to be send to unomi, check for them and filter them out.
wem._filterUnomiEvents();
// Add referrer info into digitalData.page object.
wem._processReferrer();
// Build view event
const viewEvent = wem.buildEvent('view', wem.buildTargetPage(), wem.buildSource(wem.digitalData.site.siteInfo.siteID, 'site'));
viewEvent.flattenedProperties = {};
// Add URLParameters
if (location.search) {
viewEvent.flattenedProperties['URLParameters'] = wem.convertUrlParametersToObj(location.search);
}
// Add interests
if (wem.digitalData.interests) {
viewEvent.flattenedProperties['interests'] = wem.digitalData.interests;
}
// Register the page view event, it's unshift because it should be the first event, this is just for logical purpose. (page view comes before perso displayed event for example)
wem._registerEvent(viewEvent, true);
if (wem.activateWem) {
wem.loadContext();
} else {
wem._executeFallback('wem is not activated on current page');
}
});
},
/**
* get the current loaded context from Unomi, will be accessible only after loadContext() have been performed
* @returns {any} loaded context
*/
getLoadedContext: function () {
return wem.cxs;
},
/**
* In case Unomi contains rules related to HTML forms in the current page.
* The logic is simple, in case a rule exists in Unomi targeting a form event within the current webpage path
* - then this form will be identified as form to be watched.
* You can reuse this function to get the list of concerned forms in order to attach listeners automatically for those form for example
* (not that current tracker is doing that by default, check function: _registerListenersForTrackedConditions())
* @returns {string[]} form names/ids in current web page
*/
getFormNamesToWatch: function () {
return wem.formNamesToWatch;
},
/**
* Get current session id
* @returns {null|string} get current session id
*/
getSessionId: function () {
return wem.sessionID;
},
/**
* This function will register a personalization
*
* @param {Personalization} personalization the personalization object
* @param {Record<string, Variant>} variants the variants
* @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (ignored)
* @param {function} [resultCallback] the callback to be executed after personalization resolved
* @returns {undefined}
*/
registerPersonalizationObject: function (personalization, variants, ajax, resultCallback) {
var target = personalization.id;
wem._registerPersonalizationCallback(personalization, function (result, additionalResultInfos) {
var selectedFilter = null;
var successfulFilters = [];
var inControlGroup = additionalResultInfos && additionalResultInfos.inControlGroup;
// In case of control group Unomi is not resolving any strategy or fallback for us. So we have to do the fallback here.
if (inControlGroup && personalization.strategyOptions && personalization.strategyOptions.fallback) {
selectedFilter = variants[personalization.strategyOptions.fallback];
successfulFilters.push(selectedFilter);
} else {
for (var i = 0; i < result.length; i++) {
successfulFilters.push(variants[result[i]]);
}
if (successfulFilters.length > 0) {
selectedFilter = successfulFilters[0];
var minPos = successfulFilters[0].position;
if (minPos >= 0) {
for (var j = 1; j < successfulFilters.length; j++) {
if (successfulFilters[j].position < minPos) {
selectedFilter = successfulFilters[j];
}
}
}
}
}
if (resultCallback) {
// execute callback
resultCallback(successfulFilters, selectedFilter);
} else {
if (selectedFilter) {
var targetFilters = /** @type {HTMLElement} */(document.getElementById(target)).children;
for (var fIndex in targetFilters) {
// @ts-expect-error The indexing is unsafe
var filter = /** @type {HTMLElement | null} */(targetFilters.item(fIndex));
if (filter) {
filter.style.display = (filter.id === selectedFilter.content) ? '' : 'none';
}
}
if (selectedFilter.event) {
// we now add control group information to event if the user is in the control group.
if (inControlGroup) {
console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...');
// @ts-expect-error The properties are not defined
selectedFilter.event.target.properties.inControlGroup = true;
// @ts-expect-error The properties are not defined
if (selectedFilter.event.target.properties.variants) {
// @ts-expect-error The properties are not defined
selectedFilter.event.target.properties.variants.forEach(variant => variant.inControlGroup = true);
}
}
// send event to unomi
wem.collectEvent(wem._completeEvent(selectedFilter.event), function () {
console.debug('[WEM] Personalization event successfully collected.');
}, function () {
console.error('[WEM] Could not send personalization event.');
});
//Trigger variant display event for personalization
wem._dispatchJSExperienceDisplayedEvent(selectedFilter.event);
}
} else {
var elements = /** @type {HTMLElement} */(document.getElementById(target)).children;
for (var eIndex in elements) {
// @ts-expect-error The indexing is unsafe
var el = /** @type {HTMLElement} */(elements.item(eIndex));
el.style.display = 'none';
}
}
}
});
},
/**
* This function will register an optimization test or A/B test
*
* @param {string} optimizationTestNodeId the optimization test node id
* @param {string} goalId the associated goal Id (unused)
* @param {string} containerId the HTML container Id (unused)
* @param {Record<string, Variant>} variants the variants
* @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (unused)
* @param {Record<string, number>} [variantsTraffic] the associated traffic allocation
* @return {undefined}
*/
registerOptimizationTest: function (optimizationTestNodeId, goalId, containerId, variants, ajax, variantsTraffic) {
// check persona panel forced variant
var selectedVariantId = wem.getUrlParameter('wemSelectedVariantId-' + optimizationTestNodeId);
// check already resolved variant stored in local
if (selectedVariantId === null) {
if (wem.storageAvailable('sessionStorage')) {
selectedVariantId = sessionStorage.getItem(optimizationTestNodeId);
} else {
selectedVariantId = wem.getCookie('selectedVariantId');
if (selectedVariantId != null && selectedVariantId === '') {
selectedVariantId = null;
}
}
}
// select random variant and call unomi
if (!(selectedVariantId && variants[selectedVariantId])) {
var keys = Object.keys(variants);
if (variantsTraffic) {
var rand = 100 * Math.random() << 0;
for (var nodeIdentifier in variantsTraffic) {
if ((rand -= variantsTraffic[nodeIdentifier]) < 0 && selectedVariantId == null) {
selectedVariantId = nodeIdentifier;
}
}
} else {
selectedVariantId = keys[keys.length * Math.random() << 0];
}
if (wem.storageAvailable('sessionStorage')) {
sessionStorage.setItem(optimizationTestNodeId, /** @type {string} */(selectedVariantId));
} else {
wem.setCookie('selectedVariantId', /** @type {string} */(selectedVariantId), 1);
}
const variant = variants[/** @type {string} */(selectedVariantId)];
// spread event to unomi
if (variant.event) {
wem._registerEvent(wem._completeEvent(variant.event));
}
}
if (selectedVariantId) {
// update persona panel selected variant
if (window.optimizedContentAreas && window.optimizedContentAreas[optimizationTestNodeId]) {
window.optimizedContentAreas[optimizationTestNodeId].selectedVariant = selectedVariantId;
}
// display the good variant
/** @type {HTMLElement} */(document.getElementById(variants[selectedVariantId].content)).style.display = '';
}
},
/**
* This function is used to load the current context in the page
*
* @param {boolean} [skipEvents=false] Should we send the events
* @param {boolean} [invalidate=false] Should we invalidate the current context
* @param {boolean} [forceReload=false] This function contains an internal check to avoid loading of the context multiple times.
* But in some rare cases, it could be useful to force the reloading of the context and bypass the check.
* @return {undefined}
*/
loadContext: function (skipEvents = false, invalidate = false, forceReload = false) {
if (wem.contextLoaded && !forceReload) {
console.log('Context already requested by', wem.contextLoaded);
return;
}
/** @type {Record<string, unknown>} */
var jsonData = {
requiredProfileProperties: wem.digitalData.wemInitConfig.requiredProfileProperties,
requiredSessionProperties: wem.digitalData.wemInitConfig.requiredSessionProperties,
requireSegments: wem.digitalData.wemInitConfig.requireSegments,
requireScores: wem.digitalData.wemInitConfig.requireScores,
source: wem.buildSourcePage()
};
if (!skipEvents) {
jsonData.events = wem.digitalData.events;
}
if (wem.digitalData.personalizationCallback) {
jsonData.personalizations = wem.digitalData.personalizationCallback.map(function (x) {
return x.personalization;
});
}
jsonData.sessionId = wem.sessionID;
var contextUrl = wem.contextServerUrl + '/context.json';
if (invalidate) {
contextUrl += '?invalidateSession=true&invalidateProfile=true';
}
wem.ajax({
url: contextUrl,
type: 'POST',
async: true,
contentType: 'text/plain;charset=UTF-8', // Use text/plain to avoid CORS preflight
jsonData: jsonData,
dataType: 'application/json',
// @ts-expect-error This parameter does not exist
invalidate: invalidate,
success: wem._onSuccess,
error: function () {
wem._executeFallback('error during context loading');
}
});
wem.contextLoaded = Error().stack;
console.info('[WEM] context loading...');
},
// eslint-disable-next-line valid-jsdoc
/**
* This function will send an event to Apache Unomi
* @param {UnomiEvent} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
* @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
* @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvent: function (event, successCallback = undefined, errorCallback = undefined) {
wem.collectEvents({ events: [event] }, successCallback, errorCallback);
},
// eslint-disable-next-line valid-jsdoc
/**
* This function will send the events to Apache Unomi
*
* @param {{ sessionId?: string, events: Array<UnomiEvent> }} events Javascript object { events: [event1, event2] }
* @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
* @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvents: function (events, successCallback = undefined, errorCallback = undefined) {
if (wem.fallback) {
// in case of fallback we don't want to collect any events
return;
}
events.sessionId = wem.sessionID ? wem.sessionID : '';
var data = JSON.stringify(events);
wem.ajax({
url: wem.contextServerUrl + '/eventcollector',
type: 'POST',
async: true,
contentType: 'text/plain;charset=UTF-8', // Use text/plain to avoid CORS preflight
data: data,
dataType: 'application/json',
success: successCallback,
error: errorCallback
});
},
// eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type click and send it to Apache Unomi
*
* @param {Event & { target: HTMLElement & { name: string }}} event javascript
* @param {function} [successCallback] optional, will be executed if case of success
* @param {function} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
sendClickEvent: function (event, successCallback = undefined, errorCallback = undefined) {
if (event.target.id || event.target.name) {
console.debug('[WEM] Send click event');
var targetId = event.target.id ? event.target.id : event.target.name;
var clickEvent = wem.buildEvent('click',
wem.buildTarget(targetId, event.target.localName),
wem.buildSourcePage());
var eventIndex = wem.eventsPrevented.indexOf(targetId);
if (eventIndex !== -1) {
wem.eventsPrevented.splice(eventIndex, 0);
} else {
wem.eventsPrevented.push(targetId);
event.preventDefault();
var target = event.target;
wem.collectEvent(clickEvent, function (xhr) {
console.debug('[WEM] Click event successfully collected.');
if (successCallback) {
successCallback(xhr);
} else {
target.click();
}
}, function (xhr) {
console.error('[WEM] Could not send click event.');
if (errorCallback) {
errorCallback(xhr);
} else {
target.click();
}
});
}
}
},
// eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type video and send it to Apache Unomi
*
* @param {Event} event javascript
* @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed if case of success
* @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
sendVideoEvent: function (event, successCallback = undefined, errorCallback = undefined) {
console.debug('[WEM] catching video event');
var videoEvent = wem.buildEvent('video', wem.buildTarget(/** @type {HTMLElement} */(event.target).id, 'video', { action: event.type }), wem.buildSourcePage());
wem.collectEvent(videoEvent, function (xhr) {
console.debug('[WEM] Video event successfully collected.');
if (successCallback) {
successCallback(xhr);
}
}, function (xhr) {
console.error('[WEM] Could not send video event.');
if (errorCallback) {
errorCallback(xhr);
}
});
},
/**
* This function will invalidate the Apache Unomi session and profile,
* by removing the associated cookies, set the loaded context to undefined
* and set the session id cookie with a newly generated ID
* @return {undefined}
*/
invalidateSessionAndProfile: function () {
'use strict';
wem.sessionID = wem.generateGuid() + wem.browserGeneratedSessionSuffix;
wem.setCookie(wem.trackerSessionIdCookieName, wem.sessionID, 1);
wem.removeCookie(wem.contextServerCookieName);
wem.removeCookie(wem.trackerProfileIdCookieName);
wem.cxs = undefined;
},
// eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for an event, it must be adapted to your need
*
* @param {string} eventType The name of your event
* @param {UnomiEvent["target"]} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
* @param {UnomiEvent["source"]} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
* @returns {UnomiEvent} the event
*/
buildEvent: function (eventType, target, source) {
/** @type {UnomiEvent} */
var event = {
eventType: eventType,
scope: wem.digitalData.scope
};
if (target) {
event.target = target;
}
if (source) {
event.source = source;
}
return event;
},
/**
* This function return an event of type form
*
* @param {string} formName The HTML name of id of the form to use in the target of the event
* @param {HTMLFormElement} [form] optional HTML form element, if provided will be used to extract the form fields and populate the form event
* @returns {UnomiEvent} the form event
*/
buildFormEvent: function (formName, form = undefined) {
const formEvent = wem.buildEvent('form', wem.buildTarget(formName, 'form'), wem.buildSourcePage());
formEvent.flattenedProperties = {
fields: form ? wem._extractFormData(form) : {}
};
return formEvent;
},
/**
* @param {string} formName form name
* @param {HTMLFormElement} form form
* @param {string} term term
* @param {string} language language
* @returns {UnomiEvent} event
*/
buildSearchEvent: function (formName, form, term, language) {
const searchEvent = wem.buildEvent('search', wem.buildTarget(formName, 'search'), wem.buildSourcePage());
searchEvent.flattenedProperties = {
fields: form ? wem._extractFormData(form) : {}
};
searchEvent.properties = {
originForm: formName,
language: language || 'en',
keyword: term,
// @ts-expect-error There is no way this is properly defined
origin: searchEvent.source.properties.pageInfo.pagePath
};
return searchEvent;
},
// eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
* @returns {UnomiEvent["target"]} the target page
*/
buildTargetPage: function () {
return wem.buildTarget(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
// eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
* @returns {UnomiEvent["source"]} the source page
*/
buildSourcePage: function () {
return wem.buildSource(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
// eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the target of your event
*
* @param {string} targetId The ID of the target
* @param {string} targetType The type of the target
* @param {UnomiProperties} [targetProperties] The optional properties of the target
* @returns {UnomiEvent["target"]} the target
*/
buildTarget: function (targetId, targetType, targetProperties = undefined) {
return wem._buildObject(targetId, targetType, targetProperties);
},
// eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the source of your event
*
* @param {string} sourceId The ID of the source
* @param {string} sourceType The type of the source
* @param {UnomiProperties} [sourceProperties] The optional properties of the source
* @returns {UnomiEvent["source"]} the source
*/
buildSource: function (sourceId, sourceType, sourceProperties = undefined) {
return wem._buildObject(sourceId, sourceType, sourceProperties);
},
/*************************************/
/* Utility functions under this line */
/*************************************/
/**
* This is an utility function to set a cookie
*
* @param {string} cookieName name of the cookie
* @param {string} cookieValue value of the cookie
* @param {number} [expireDays] number of days to set the expire date
* @return {undefined}
*/
setCookie: function (cookieName, cookieValue, expireDays) {
let expires = '';
if (expireDays) {
var d = new Date();
d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000));
expires = '; expires=' + d.toUTCString();
}
let secure = location.protocol === 'https:' ? '; secure' : '';
document.cookie = cookieName + '=' + cookieValue + expires + '; path=/; SameSite=Strict' + secure;
},
/**
* This is an utility function to get a cookie
*
* @param {string} cookieName name of the cookie to get
* @returns {string | null} the value of the first cookie with the corresponding name or null if not found
*/
getCookie: function (cookieName) {
var name = cookieName + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return null;
},
/**
* This is an utility function to remove a cookie
*
* @param {string} cookieName the name of the cookie to rename
* @return {undefined}
*/
removeCookie: function (cookieName) {
'use strict';
wem.setCookie(cookieName, '', -1);
},
/**
* This is an utility function to execute AJAX call
*
* @param {AjaxOptions} options options of the request
* @return {undefined}
*/
ajax: function (options) {
var xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open(options.type, options.url, options.async);
xhr.withCredentials = true;
} else if (typeof XDomainRequest != 'undefined') {
/* global XDomainRequest */
xhr = new XDomainRequest();
xhr.open(options.type, options.url);
}
if (options.contentType) {
xhr.setRequestHeader('Content-Type', options.contentType);
}
if (options.dataType) {
xhr.setRequestHeader('Accept', options.dataType);
}
if (options.responseType) {
xhr.responseType = options.responseType;
}
var requestExecuted = false;
if (wem.timeoutInMilliseconds !== -1) {
setTimeout(function () {
if (!requestExecuted) {
console.error('[WEM] XML request timeout, url: ' + options.url);
requestExecuted = true;
if (options.error) {
options.error(xhr);
}
}
}, wem.timeoutInMilliseconds);
}
xhr.onreadystatechange = function () {
if (!requestExecuted) {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 204 || xhr.status === 304) {
if (xhr.responseText != null) {
requestExecuted = true;
if (options.success) {
options.success(xhr);
}
}
} else {
requestExecuted = true;
if (options.error) {
options.error(xhr);
}
console.error('[WEM] XML request error: ' + xhr.statusText + ' (' + xhr.status + ')');
}
}
}
};
if (options.jsonData) {
xhr.send(JSON.stringify(options.jsonData));
} else if (options.data) {
xhr.send(options.data);
} else {
xhr.send();
}
},
/**
* This is an utility function to generate a new UUID
*
* @returns {string} the newly generated UUID
*/
generateGuid: function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
},
/**
* This is an utility function to check if the local storage is available or not
* @param {"sessionStorage" | "localStorage"} type the type of storage to test
* @returns {boolean} true in case storage is available, false otherwise
*/
storageAvailable: function (type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return false;
}
},
/**
* Dispatch a JavaScript event in current HTML document
*
* @param {string} name the name of the event
* @param {boolean} canBubble does the event can bubble ?
* @param {boolean} cancelable is the event cancelable ?
* @param {*} detail event details
* @return {undefined}
*/
dispatchJSEvent: function (name, canBubble, cancelable, detail) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent(name, canBubble, cancelable, detail);
document.dispatchEvent(event);
},
/**
* Fill the wem.digitalData.displayedVariants with the javascript event passed as parameter
* @param {object} jsEvent javascript event
* @private
* @return {undefined}
*/
_fillDisplayedVariants: (jsEvent) => {
if (!wem.digitalData.displayedVariants) {
wem.digitalData.displayedVariants = [];
}
wem.digitalData.displayedVariants.push(jsEvent);
},
/**
* This is an utility function to get current url parameter value
*
* @param {string} name, the name of the parameter
* @returns {string | null} the value of the parameter
*/
getUrlParameter: function (name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(window.location.search);
return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
},
/**
* convert the passed query string into JS object.
* @param {string} searchString The URL query string
* @returns {Record<string, Array<string | undefined> | string | undefined> | null} converted URL params
*/
convertUrlParametersToObj: function (searchString) {
if (!searchString) {
return null;
}
return searchString
.replace(/^\?/, '') // Only trim off a single leading interrobang.
.split('&')
.reduce((result, next) => {
if (next === '') {
return result;
}
let pair = next.split('=');
let key = decodeURIComponent(pair[0]);
let value = typeof pair[1] !== 'undefined' && decodeURIComponent(pair[1]) || undefined;
if (Object.prototype.hasOwnProperty.call(result, key)) { // Check to see if this property has been met before.
if (Array.isArray(result[key])) { // Is it already an array?
result[key].push(value);
} else { // Make it an array.
result[key] = [result[key], value];
}
} else { // First time seen, just add it.
result[key] = value;
}
return result;
}, /** @type Record<string, Array<string | undefined> | string | undefined> */({})
);
},
/*************************************/
/* Private functions under this line */
/*************************************/
/**
* Used to override the default digitalData values,
* the result will impact directly the current instance wem.digitalData
*
* @param {Array<Partial<DigitalData>>} [digitalDataOverrides] list of overrides
* @private
* @return {undefined}
*/
_handleDigitalDataOverrides: function (digitalDataOverrides) {
if (digitalDataOverrides && digitalDataOverrides.length > 0) {
for (const digitalDataOverride of digitalDataOverrides) {
wem.digitalData = wem._deepMergeObjects(digitalDataOverride, wem.digitalData);
}
}
},
/**
* Check for tracked conditions in the current loaded context, and attach listeners for the known tracked condition types:
* - formEventCondition
* - videoViewEventCondition
* - clickOnLinkEventCondition
*
* @private
* @return {undefined}
*/
_registerListenersForTrackedConditions: function () {
console.debug('[WEM] Check for tracked conditions and attach related HTML listeners');
var videoNamesToWatch = [];
var clickToWatch = [];
if (wem.cxs.trackedConditions && wem.cxs.trackedConditions.length > 0) {
for (var i = 0; i < wem.cxs.trackedConditions.length; i++) {
switch (wem.cxs.trackedConditions[i].type) {
case 'formEventCondition':
if (wem.cxs.trackedConditions[i].parameterValues && wem.cxs.trackedConditions[i].parameterValues.formId) {
wem.formNamesToWatch.push(wem.cxs.trackedConditions[i].parameterValues.formId);
}
break;
case 'videoViewEventCondition':
if (wem.cxs.trackedConditions[i].parameterValues && wem.cxs.trackedConditions[i].parameterValues.videoId) {
videoNamesToWatch.push(wem.cxs.trackedConditions[i].parameterValues.videoId);
}
break;
case 'clickOnLinkEventCondition':
if (wem.cxs.trackedConditions[i].parameterValues && wem.cxs.trackedConditions[i].parameterValues.itemId) {
clickToWatch.push(wem.cxs.trackedConditions[i].parameterValues.itemId);
}
break;
}
}
}
var forms = document.querySelectorAll('form');
for (var formIndex = 0; formIndex < forms.length; formIndex++) {
var form = forms.item(formIndex);
var formName = form.getAttribute('name') ? form.getAttribute('name') : form.getAttribute('id');
// test attribute data-form-id to not add a listener on FF form
if (formName && wem.formNamesToWatch.indexOf(formName) > -1 && form.getAttribute('data-form-id') == null) {
// add submit listener on form that we need to watch only
console.debug('[WEM] Watching form ' + formName);
form.addEventListener('submit', wem._formSubmitEventListener, true);
}
}
for (var videoIndex = 0; videoIndex < videoNamesToWatch.length; videoIndex++) {
var videoName = videoNamesToWatch[videoIndex];
var video = document.getElementById(videoName) || document.getElementById(wem._resolveId(videoName));
if (video) {
video.addEventListener('play', wem.sendVideoEvent);
video.addEventListener('ended', wem.sendVideoEvent);
console.debug('[WEM] Watching video ' + videoName);
} else {
console.warn('[WEM] Unable to watch video ' + videoName + ', video not found in the page');
}
}
for (var clickIndex = 0; clickIndex < clickToWatch.length; clickIndex++) {
var clickIdName = clickToWatch[clickIndex];
var click = (document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)))
? (document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)))
: document.getElementsByName(clickIdName)[0];
if (click) {
// @ts-expect-error The types will never match
click.addEventListener('click', wem.sendClickEvent);
console.debug('[WEM] Watching click ' + clickIdName);
} else {
console.warn('[WEM] Unable to watch click ' + clickIdName + ', element not found in the page');
}
}
},
/**
* Check for currently registered events in wem.digitalData.events that would be incomplete:
* - autocomplete the event with the current digitalData page infos for the source
* @private
* @return {undefined}
*/
_checkUncompleteRegisteredEvents: function () {
if (wem.digitalData && wem.digitalData.events) {
for (const event of wem.digitalData.events) {
wem._completeEvent(event);
}
}
},
/**
* dispatch JavaScript event in current HTML document for perso and opti events contains in digitalData.events
* @private
* @return {undefined}
*/
_dispatchJSExperienceDisplayedEvents: () => {
if (wem.digitalData && wem.digitalData.events) {
for (const event of wem.digitalData.events) {
if (event.eventType === 'optimizationTestEvent' || event.eventType === 'personalizationEvent') {
wem._dispatchJSExperienceDisplayedEvent(event);
}
}
}
},
/**
* build and dispatch JavaScript event in current HTML document for the given Unomi event (perso/opti)
* @private
* @param {UnomiEvent} experienceUnomiEvent perso/opti Unomi event
* @return {undefined}
*/
_dispatchJSExperienceDisplayedEvent: experienceUnomiEvent => {
if (!wem.fallback &&
experienceUnomiEvent &&
experienceUnomiEvent.target &&
experienceUnomiEvent.target.properties &&
experienceUnomiEvent.target.properties.variants &&
experienceUnomiEvent.target.properties.variants.length > 0) {
/** @type {Record<string, string | undefined>} */