-
Notifications
You must be signed in to change notification settings - Fork 0
/
gtm_tag-google_ecommerce_data_transfer.js
1164 lines (1099 loc) · 58.9 KB
/
gtm_tag-google_ecommerce_data_transfer.js
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
<script>
// Custom HTML Tag for Google Tag Manager
// Google Enhanced Ecommerce data transfer to remarketing pixels
// v.1.01
//
// Available pixels:
// VK (https://vk.com)
// Facebook (https://facebook.com)
// myTarget (https://target.my.com)
//
// Developer: https://github.com/oleg-dirtrider
//
// Fill the settings and install this tag in GTM via All Pages trigger
(function() {
// Fill the settings
var settings = {
// Pixels you want to send data to
pixels: {
vk: true,
facebook: true,
myTarget: true
},
// VK pixel settings
vk: {
// Pixel ID. Even if there is only one pixel, you must specify its ID in the array
pixelIDs: ['vk_pixel_id_1', 'vk_pixel_id_2'],
// If you want to use several price lists, set the value to true, otherwise set false
fewPriceLists: true,
// Price list ID if you want yo use one price list
priceListId: 1234,
// Dictionary "host - price list ID", if you want to use several price lists
priceListIds: {
'moscow.example.ru': 1111,
'spb.example.ru': 2222
},
// Install VK pixel base code. If a VK pixel(s) is(are) already installed on the site, installation of the base code isn't required
baseCode: true,
// Default currency
defaultCurrency: 'RUB'
},
// Facebook pixel settings
facebook: {
// Pixel ID. Even if there is only one pixel, you must specify its ID in the array
pixelIDs: ['facebook_pixel_id_1', 'facebook_pixel_id_2'],
// Install Facebook pixel base code. If a Facebook pixel(s) is(are) already installed on the site, installation of the base code isn't required
baseCode: true,
// Default currency
defaultCurrency: 'RUB'
},
// myTarget counter settings
myTarget: {
// Pixel ID. Even if there is only one pixel, you must specify its ID in the array
pixelIDs: ['myTarget_counter_id_1', 'myTarget_counter_id_2'],
// If you want to use several price lists, set the value to true, otherwise set false
fewPriceLists: true,
// Price list ID if you want yo use one price list
priceListId: '111',
// Dictionary "host - price list ID", if you want to use several price lists
priceListIds: {
'moscow.example.ru': '111',
'spb.example.ru': '222'
},
// Install myTarget counter base code. If a myTarget counter(s) is(are) already installed on the site, installation of the base code isn't required
baseCode: true
},
// If the page type is passed from the site to a GTM variable, you can use it to determine the page type
useGTMvarPageType: false,
// GTM page type variable name
pageTypeGTM: "",
// GTM page type variable value(s) for site pages
pageTypeGTMnames: {
// GTM page type variable value for the home page of the site
main: 'example_main_page',
// GTM page type variable value(s) for the catalog site page(s). Even if there is only one catalog page value, you must specify it in the array
catalog: ['example_catalog_page_1', 'example_catalog_page_2'],
// GTM page type variable value for the site search page of the site
siteSearch: 'example_siteSearch_page'
},
// If the page type is NOT passed from the site to a GTM variable, you should to set regular expressions that identifies the site pages
// Regular expression that identifies the home site page
mainPage: 'example\\.ru\\/($|\\?)',
// Regular expression that identifies the catalog site page(s)
catalogPage: 'example\\.ru\\/catalog\\/',
// Regular expression that identifies a site page with site search results
siteSearch: 'search\\.html',
// Site search query URL parameter
siteSearchQueryParam: 'query',
siteSearchPage: this.useGTMvarPageType ? this.pageTypeGTMnames.siteSearch : this.siteSearch,
// Debug Mode logs different messages to the console during tag running
// Don't forget to disable Debug Mode before publishing the container to the site!
debug: false
};
// Data transfer function
if (!window.gaEcomTransfer) window.gaEcomTransfer = function(settings) {
var main = {
vk: {
// Name of the object to display in the console when the debug mode is activated
debugName: 'vk',
// Console output decoration when the debug mode is activated
debugCSS: 'background-color: PowderBlue;',
// Matching GA Enhanced Ecommerce events and VK pixel events
eventsEcomm: {
impressions: ['view_home', 'view_category', 'view_search', 'view_other'],
detail: 'view_product',
add: 'add_to_cart',
remove: 'remove_from_cart',
checkout: 'init_checkout',
purchase: 'purchase'
},
// Openapi.js load waiting counter
openapiLoadCounter: 0,
/**
* Getting the event name for a pixel.
* @param {string} ecommEventName - GA Ecommerce event name.
* @returns {string} VK pixel event name.
*/
getEventName: function(ecommEventName) {
debug.log_start.call(this, 'vk.getEventName');
if (ecommEventName !== 'impressions') {
return this.eventsEcomm[ecommEventName];
}
else if (main.event.getPageType() === 'main') {
return this.eventsEcomm.impressions[0];
}
else if (main.event.getPageType() === 'catalog') {
return this.eventsEcomm.impressions[1];
}
else if (main.event.getPageType() === 'search') {
return this.eventsEcomm.impressions[2];
}
else {
return this.eventsEcomm.impressions[3];
}
},
/**
* Getting event parameters for a pixel.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
* @param {string} ecommEventName - GA Ecommerce event name.
* @returns {Object} Processed event parameters.
*/
getEventParams: function(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue, ecommEventName) {
debug.log_start.call(this, 'vk.getEventParams');
var eventParams = new this.eventParamConstructor(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue);
if (ecommEventName === 'impressions') {
eventParams.total_price = undefined;
eventParams.currency_code = undefined;
}
for (var param in eventParams) {
if (!eventParams[param]) {
delete eventParams[param];
}
}
return eventParams;
},
/**
* Event parameters object constructor.
* @constructs eventParam
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
*/
eventParamConstructor: function(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue) {
debug.log_start.call(main.vk, 'vk.eventParamConstructor');
this.products = main.vk.getProductParams(ecommEventProducts);
this.category_ids = main.products.getCategoryString(ecommEventProducts);
this.currency_code = main.products.getCurrencyCode('vk', ecommEventCurrencyCode);
this.total_price = main.products.getTotalPrice(ecommEventProducts, ecommEventRevenue);
this.search_string = main.event.getSiteSearchPhrase();
},
/**
* Getting the parameters of the product object for a pixel.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @returns {Object[]} Product parameters.
*/
getProductParams: function(ecommEventProducts) {
debug.log_start.call(this, 'vk.getProductParams');
var arr = [];
for (var i = 0; i < ecommEventProducts.length; i++) {
var productParams = {
id: String(ecommEventProducts[i].id),
group_id: String(ecommEventProducts[i].brand),
price: (parseInt(ecommEventProducts[i].price * 100, 10)) / 100
};
for (var param in productParams) {
if (!productParams[param]) {
delete productParams[param];
}
}
arr.push(productParams);
}
return arr;
},
/**
* Price list selection.
* @param {string} hostname - Page hostname.
* @returns {string} Price list ID.
*/
getPriceListId: function(hostname) {
debug.log_start.call(this, 'vk.getPriceListId');
if (settings.vk.fewPriceLists) {
return settings.vk.priceListIds[hostname];
}
else {
return settings.vk.priceListId;
}
},
/**
* VK base code inject.
*/
openapiInit: function() {
debug.log_start.call(this, 'vk.openapiInit');
if (document.getElementById('vk_api_transport')) {
debug.log.call(this, 'Failed to load openapi.js');
return;
}
var openapi = document.createElement('div');
var body = document.getElementsByTagName('body')[0];
var el = document.createElement('script');
openapi.id = 'vk_api_transport';
body.insertBefore(openapi, body.firstChild);
el.type = 'text/javascript';
el.src = 'https://vk.com/js/api/openapi.js?159';
el.async = true;
document.getElementById('vk_api_transport').appendChild(el);
debug.log.call(this, 'Div with openapi.js was installed');
},
/**
* VK pixel initialization.
* @param {string} pixelID - VK pixel ID.
*/
pixelInit: function(pixelID) {
debug.log_start.call(this, 'vk.pixelInit');
VK.Retargeting.Init(pixelID);
debug.log.call(this, 'Pixel was initialized:', pixelID);
},
/**
* Sending pageview to VK pixel.
*/
sendPageView: function() {
debug.log_start.call(main.vk, 'vk.sendPageView');
if (window.VK) {
debug.log.call(main.vk, 'Sending pageview to VK pixel...');
for (var i = 0; i < settings.vk.pixelIDs.length; i++) {
main.vk.pixelInit(settings.vk.pixelIDs[i]);
VK.Retargeting.Hit();
debug.log.call(main.vk, 'Pageview was sent to', settings.vk.pixelIDs[i]);
}
}
else if (document.getElementById('vk_api_transport') && main.vk.openapiLoadCounter < 100) {
debug.log.call(main.vk, 'VK base code not found, waiting for openapi.js load... Attempts left:', 99 - main.vk.openapiLoadCounter);
setTimeout(main.vk.sendPageView, 100);
main.vk.openapiLoadCounter++;
}
else {
debug.log.call(main.vk, 'VK base code not found, trying to install openapi.js...');
main.vk.openapiInit();
window.vkAsyncInit = function() {
debug.log.call(main.vk, 'vkAsyncInit: sending pageview to VK pixel...');
for (var i = 0; i < settings.vk.pixelIDs.length; i++) {
main.vk.pixelInit(settings.vk.pixelIDs[i]);
VK.Retargeting.Hit();
debug.log.call(main.vk, 'Pageview was sent to', settings.vk.pixelIDs[i]);
}
};
}
},
/**
* Sending event data to VK pixel.
* @param {string} ecommEventName - GA Ecommerce event name.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
*/
sendEvent: function(ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue) {
debug.log_start.call(main.vk, 'vk.sendEvent');
if (window.VK) {
debug.log.call(main.vk, 'Sending event data to VK pixel...');
var pixelEvent = new main.event.eventConstructor('vk', ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue);
var priсeListID = main.vk.getPriceListId(main.url.host);
var name = pixelEvent.name;
var params = pixelEvent.params;
if (!settings.vk.pixelIDs) {
VK.Retargeting.ProductEvent(priсeListID, name, params);
debug.log.call(main.vk, 'Event data:', priсeListID, name, params, 'was sent to VK pixel');
}
else {
for (var i = 0; i < settings.vk.pixelIDs.length; i++) {
main.vk.pixelInit(settings.vk.pixelIDs[i]);
VK.Retargeting.ProductEvent(priсeListID, name, params);
debug.log.call(main.vk, 'Event data:', priсeListID, name, params, 'was sent to', settings.vk.pixelIDs[i]);
}
}
}
else if (document.getElementById('vk_api_transport') && main.vk.openapiLoadCounter < 100) {
debug.log.call(main.vk, 'VK base code not found, waiting for openapi.js load... Attempts left:', 99 - main.vk.openapiLoadCounter);
setTimeout(main.vk.sendEvent, 100, ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue);
main.vk.openapiLoadCounter++;
}
else {
debug.log.call(main.vk, 'VK base code not found, event data cannot be sent to VK pixel');
return;
}
}
},
facebook: {
// Name of the object to display in the console when the debug mode is activated
debugName: 'facebook',
// Console output decoration when the debug mode is activated
debugCSS: 'background-color: Plum;',
// Matching GA Enhanced Ecommerce events and Facebook pixel events
eventsEcomm: {
impressions: ['ViewHome', 'ViewCategory', 'Search', 'ViewOther'],
detail: 'ViewContent',
add: 'AddToCart',
remove: 'RemoveFromCart',
checkout: 'InitiateCheckout',
purchase: 'Purchase'
},
/**
* Getting the event name for a pixel.
* @param {string} ecommEventName - GA Ecommerce event name.
* @returns {string} Facebook pixel event name.
*/
getEventName: function(ecommEventName) {
debug.log_start.call(this, 'facebook.getEventName');
if (ecommEventName !== 'impressions') {
return this.eventsEcomm[ecommEventName];
}
else if (main.event.getPageType() === 'main') {
return this.eventsEcomm.impressions[0];
}
else if (main.event.getPageType() === 'catalog') {
return this.eventsEcomm.impressions[1];
}
else if (main.event.getPageType() === 'search') {
return this.eventsEcomm.impressions[2];
}
else {
return this.eventsEcomm.impressions[3];
}
},
/**
* Getting event parameters for a pixel.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
* @param {string} ecommEventName - GA Ecommerce event name.
* @returns {Object} Processed event parameters.
*/
getEventParams: function(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue, ecommEventName) {
debug.log_start.call(this, 'facebook.getEventParams');
var eventParams = new this.eventParamConstructor(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue);
if (ecommEventName === 'impressions' && main.event.getPageType() === 'search') {
return {
contents: eventParams.contents,
content_category: eventParams.content_category,
search_string: eventParams.search_string
};
}
else if (ecommEventName === 'impressions' && main.event.getPageType() !== 'search') {
return {
contents: eventParams.contents,
content_name: eventParams.content_name,
content_type: eventParams.content_type
};
}
else if (ecommEventName === 'checkout') {
return {
contents: eventParams.contents,
content_category: eventParams.content_category,
num_items: eventParams.num_items,
currency: eventParams.currency,
value: eventParams.value
};
}
else if (ecommEventName === 'purchase') {
return {
contents: eventParams.contents,
content_name: eventParams.content_name,
content_type: eventParams.content_type,
currency: eventParams.currency,
value: eventParams.value,
num_items: eventParams.num_items
};
}
else {
return {
contents: eventParams.contents,
content_name: eventParams.content_name,
content_type: eventParams.content_type,
currency: eventParams.currency,
value: eventParams.value
};
}
},
/**
* Event parameters object constructor.
* @constructs eventParam
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
*/
eventParamConstructor: function(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue) {
debug.log_start.call(main.facebook, 'facebook.eventParamConstructor');
this.contents = main.facebook.getСontents(ecommEventProducts);
this.content_name = main.products.getContentNameString(ecommEventProducts);
this.content_type = main.facebook.getContentType();
this.currency = main.products.getCurrencyCode('facebook', ecommEventCurrencyCode);
this.value = main.products.getTotalPrice(ecommEventProducts, ecommEventRevenue);
this.content_category = main.products.getCategoryString(ecommEventProducts);
this.search_string = main.event.getSiteSearchPhrase();
this.num_items = main.products.getNumItems(ecommEventProducts);
},
/**
* Getting the parameters of the contents object for a pixel.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @returns {Object[]} Product parameters.
*/
getСontents: function(ecommEventProducts) {
debug.log_start.call(this, 'facebook.getСontents');
var arr = [];
for (var i = 0; i < ecommEventProducts.length; i++) {
var productParams = {
id: String(ecommEventProducts[i].id),
quantity: parseInt(ecommEventProducts[i].quantity, 10),
item_price: (parseInt(ecommEventProducts[i].price * 100, 10)) / 100
};
for (var param in productParams) {
if (param === 'quantity' && isNaN(productParams[param])) {
productParams[param] = 1;
}
else if (!productParams[param]) {
delete productParams[param];
}
}
arr.push(productParams);
}
return arr;
},
/**
* Getting content_type parameter.
* @returns {string} content_type parameter.
*/
getContentType: function() {
debug.log_start.call(this, 'facebook.getContentType');
return 'product';
},
/**
* Facebook pixel base code inject.
*/
facebookInit: function(f, b, e, v, n, t, s) {
debug.log_start.call(this, 'facebook.facebookInit');
if (f.fbq) {
return;
}
n = f.fbq = function() {
n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
};
if (!f._fbq) {
f._fbq = n;
}
n.push = n;
n.loaded = !0;
n.version = '2.0';
n.queue = [];
t = b.createElement(e);
t.async = !0;
t.src = v;
s = b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t, s);
debug.log.call(this, 'Facebook base code was installed');
},
/**
* Facebook pixel initialization.
* @param {string} pixelID - Facebook pixel ID.
*/
pixelInit: function(pixelID) {
debug.log_start.call(this, 'facebook.pixelInit');
fbq('init', pixelID);
debug.log.call(this, 'Pixel was initialized:', pixelID);
},
/**
* Sending pageview to Facebook pixel.
*/
sendPageView: function() {
debug.log_start.call(this, 'facebook.sendPageView');
debug.log.call(this, 'Checking whether it is necessary to install Facebook base code...');
this.facebookInit(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
if (window.fbq) {
debug.log.call(this, 'Sending pageview to Facebook pixel...');
for (var i = 0; i < settings.facebook.pixelIDs.length; i++) {
this.pixelInit(settings.facebook.pixelIDs[i]);
}
fbq('track', 'PageView');
debug.log.call(this, 'Pageview was sent to', settings.facebook.pixelIDs);
}
else {
debug.log.call(this, 'Facebook base code not found, pageview cannot be sent to Facebook pixel');
return;
}
},
/**
* Sending event data to Facebook pixel.
* @param {string} ecommEventName - GA Ecommerce event name.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
*/
sendEvent: function(ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue) {
debug.log_start.call(this, 'facebook.sendEvent');
if (window.fbq) {
debug.log.call(this, 'Sending event data to Facebook pixel...');
var pixelEvent = new main.event.eventConstructor('facebook', ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue);
var name = pixelEvent.name;
var params = pixelEvent.params;
if (/^RemoveFromCart|ViewHome|ViewCategory|ViewOther$/.test(name)) {
fbq('trackCustom', name, params);
}
else {
fbq('track', name, params);
}
debug.log.call(this, 'Event data:', name, params, 'was sent to Facebook pixel');
}
else {
debug.log.call(this, 'Facebook base code not found, event data cannot be sent to Facebook pixel');
return;
}
}
},
myTarget: {
// Name of the object to display in the console when the debug mode is activated
debugName: 'myTarget',
// Console output decoration when the debug mode is activated
debugCSS: 'background-color: PeachPuff;',
// Matching GA Enhanced Ecommerce events and myTarget counter events
eventsEcomm: {
impressions: ['home', 'category', 'searchresults', 'other'],
detail: 'product',
add: 'cart',
purchase: 'purchase'
},
/**
* Getting the event name for a counter.
* @param {string} ecommEventName - GA Ecommerce event name.
* @returns {string} myTarget counter event name.
*/
getEventName: function(ecommEventName) {
debug.log_start.call(this, 'myTarget.getEventName');
if (ecommEventName !== 'impressions') {
return this.eventsEcomm[ecommEventName];
}
else if (main.event.getPageType() === 'main') {
return this.eventsEcomm.impressions[0];
}
else if (main.event.getPageType() === 'catalog') {
return this.eventsEcomm.impressions[1];
}
else if (main.event.getPageType() === 'search') {
return this.eventsEcomm.impressions[2];
}
else {
return this.eventsEcomm.impressions[3];
}
},
/**
* Getting event parameters for a counter.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
* @param {string} ecommEventName - GA Ecommerce event name.
* @returns {Object} Processed event parameters.
*/
getEventParams: function(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue, ecommEventName) {
debug.log_start.call(this, 'myTarget.getEventParams');
var eventParams = new this.eventParamConstructor(ecommEventProducts, ecommEventRevenue, ecommEventName);
if (ecommEventName === 'impressions') {
eventParams.totalvalue = undefined;
}
for (var param in eventParams) {
if (!eventParams[param]) {
delete eventParams[param];
}
}
return eventParams;
},
/**
* Event parameters object constructor.
* @constructs eventParam
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
*/
eventParamConstructor: function(ecommEventProducts, ecommEventRevenue, ecommEventName) {
debug.log_start.call(main.myTarget, 'myTarget.eventParamConstructor');
this.type = 'itemView';
this.productid = main.products.getProductsId(ecommEventProducts);
this.pagetype = main.myTarget.getEventName(ecommEventName);
this.list = main.myTarget.getPriceListId(main.url.host);
this.totalvalue = main.products.getTotalPrice(ecommEventProducts, ecommEventRevenue);
},
/**
* Product feed selection.
* @param {string} hostname - Page hostname.
* @returns {string} Product feed.
*/
getPriceListId: function(hostname) {
debug.log_start.call(this, 'myTarget.getPriceListId');
if (settings.myTarget.fewPriceLists) {
return settings.myTarget.priceListIds[hostname];
}
else {
return settings.myTarget.priceListId;
}
},
/**
* myTarget counter base code inject.
*/
myTargetInit: function(d, w, id) {
debug.log_start.call(this, 'myTarget.myTargetInit');
if (d.getElementById(id)) {
return;
}
w._tmr = [];
var ts = d.createElement('script');
ts.type = 'text/javascript';
ts.async = true;
ts.id = id;
ts.src = (d.location.protocol == 'https:' ? 'https:' : 'http:') + '//top-fwz1.mail.ru/js/code.js';
var f = function() {
var s = d.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ts, s);
};
if (w.opera == '[object Opera]') {
d.addEventListener('DOMContentLoaded', f, false);
}
else {
f();
}
debug.log.call(this, 'myTarget counter base code was installed');
},
/**
* Sending pageview to myTarget counter.
*/
sendPageView: function() {
debug.log_start.call(this, 'myTarget.sendPageView');
debug.log.call(this, 'Checking whether it is necessary to install myTarget counter base code...');
this.myTargetInit(document, window, 'topmailru-code');
if (window._tmr) {
debug.log.call(this, 'Sending pageview to myTarget counter...');
for (var i = 0; i < settings.myTarget.pixelIDs.length; i++) {
_tmr.push({
id: settings.myTarget.pixelIDs[i],
type: 'pageView',
start: (new Date()).getTime()
});
debug.log.call(this, 'Pageview was sent to', settings.myTarget.pixelIDs[i]);
}
}
else {
debug.log.call(this, 'myTarget counter base code not found, pageview cannot be sent to myTarget counter');
return;
}
},
/**
* Sending event data to myTarget counter.
* @param {string} ecommEventName - GA Ecommerce event name.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
*/
sendEvent: function(ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue) {
debug.log_start.call(this, 'myTarget.sendEvent');
if (window._tmr) {
debug.log.call(this, 'Sending event data to myTarget counter...');
var pixelEvent = new main.event.eventConstructor('myTarget', ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue);
for (var i = 0; i < settings.myTarget.pixelIDs.length; i++) {
_tmr.push({
id: settings.myTarget.pixelIDs[i],
type: pixelEvent.params.type,
productid: pixelEvent.params.productid,
pagetype: pixelEvent.params.pagetype,
list: pixelEvent.params.list,
totalvalue: pixelEvent.params.totalvalue
});
debug.log.call(this, 'Event data:', pixelEvent.params, 'was sent to', settings.myTarget.pixelIDs[i]);
}
}
else {
debug.log.call(this, 'myTarget counter base code not found, event data cannot be sent to myTarget counter');
return;
}
}
},
products: {
// Name of the object to display in the console when the debug mode is activated
debugName: 'products',
/**
* Getting a list of product categories.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @returns {string} List of product categories.
*/
getCategoryString: function(ecommEventProducts) {
debug.log_start.call(this, 'products.getCategoryString');
var categoryId = '';
var check = [];
for (var i = 0; i < ecommEventProducts.length; i++) {
if (check.indexOf(ecommEventProducts[i].category) === -1) {
check.push(ecommEventProducts[i].category);
categoryId += ',' + ecommEventProducts[i].category;
}
}
categoryId = categoryId.slice(1);
return categoryId;
},
/**
* Getting the currency of the price of the products.
* @param {string} pixel - Name of the pixel for which you want to find the currency code.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @returns {string} Currency code.
*/
getCurrencyCode: function(pixel, ecommEventCurrencyCode) {
debug.log_start.call(this, 'products.getCurrencyCode');
if (!ecommEventCurrencyCode) {
return settings[pixel].defaultCurrency;
}
else {
return ecommEventCurrencyCode;
}
},
/**
* Getting the total price of the products.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @returns {(integer|float)} Total price.
*/
getTotalPrice: function(ecommEventProducts, ecommEventRevenue) {
debug.log_start.call(this, 'products.getTotalPrice');
if (ecommEventRevenue !== 'not set') {
return (parseInt(ecommEventRevenue * 100, 10)) / 100;
}
else {
var sumPrice = 0;
for (var i = 0; i < ecommEventProducts.length; i++) {
if (ecommEventProducts[i].hasOwnProperty('quantity')) {
sumPrice += ((parseInt(ecommEventProducts[i].price * 100, 10)) / 100) * parseInt(ecommEventProducts[i].quantity, 10);
}
else {
sumPrice += (parseInt(ecommEventProducts[i].price * 100, 10)) / 100;
}
}
return sumPrice;
}
},
/**
* Getting a list of product names.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @returns {string} List of product names.
*/
getContentNameString: function(ecommEventProducts) {
debug.log_start.call(this, 'products.getContentNameString');
var contentName = '';
var check = [];
for (var i = 0; i < ecommEventProducts.length; i++) {
if (check.indexOf(ecommEventProducts[i].name) === -1) {
check.push(ecommEventProducts[i].name);
contentName += ',' + ecommEventProducts[i].name;
}
}
contentName = contentName.slice(1);
return contentName;
},
/**
* Getting the total amount of the products.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @returns {integer} Total amount of the products.
*/
getNumItems: function(ecommEventProducts) {
debug.log_start.call(this, 'products.getNumItems');
var count = 0;
for (var i = 0; i < ecommEventProducts.length; i++) {
if (ecommEventProducts[i].hasOwnProperty('quantity')) {
count += parseInt(ecommEventProducts[i].quantity, 10);
}
else {
count += 1;
}
}
return count;
},
/**
* Getting an array of product ids.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @returns {string[]} Array of product ids.
*/
getProductsId: function(ecommEventProducts) {
debug.log_start.call(this, 'products.getProductsId');
var idArr = [];
for (var i = 0; i < ecommEventProducts.length; i++) {
idArr.push(ecommEventProducts[i].id);
}
return idArr;
}
},
event: {
// Name of the object to display in the console when the debug mode is activated
debugName: 'event',
/**
* Event validation for sending data in pixels.
* @param {string} ecommEventName - GA Ecommerce event name.
* @param {Object} ecommEventObj - GA Ecommerce object.
* @returns {Object} Result of checking.
*/
eventCheck: function(ecommEventName, ecommEventObj) {
debug.log_start.call(this, 'event.eventCheck');
var eventCheckedObj = {};
for (var pixel in settings.pixels) {
if (settings.pixels[pixel]) {
if (!main[pixel].eventsEcomm.hasOwnProperty(ecommEventName)) {
eventCheckedObj[pixel] = false;
}
else if (ecommEventName === 'checkout' && ecommEventObj.hasOwnProperty('actionField') &&
ecommEventObj.actionField.hasOwnProperty('step') && parseInt(ecommEventObj.actionField.step, 10) !== 1) {
eventCheckedObj[pixel] = false;
}
else if (main[pixel].hasOwnProperty('eventCheck') && !main[pixel].eventCheck(ecommEventName, ecommEventObj)) {
eventCheckedObj[pixel] = false;
}
else {
eventCheckedObj[pixel] = true;
}
}
else {
eventCheckedObj[pixel] = false;
}
}
return eventCheckedObj;
},
/**
* Event object constructor.
* @constructs event
* @param {string} pixel - Name of the pixel for which you want to generate event object.
* @param {string} ecommEventName - GA Ecommerce event name.
* @param {Object[]} ecommEventProducts - An array of products and their parameters from the GA Ecommerce event.
* @param {string} ecommEventCurrencyCode - Currency code from the GA Ecommerce event.
* @param {(string|integer|float)} ecommEventRevenue - The total purchase amount from the GA Ecommerce event.
*/
eventConstructor: function(pixel, ecommEventName, ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue) {
debug.log_start.call(main.event, 'event.eventConstructor');
this.name = main[pixel].getEventName(ecommEventName);
this.params = main[pixel].getEventParams(ecommEventProducts, ecommEventCurrencyCode, ecommEventRevenue, ecommEventName);
},
/**
* Page type definition.
* @returns {string} Page type.
*/
getPageType: function() {
debug.log_start.call(this, 'event.getPageType');
if (settings.useGTMvarPageType) {
if (settings.pageTypeGTM === settings.pageTypeGTMnames.main) {
debug.log.call(this, 'Page type found by GTM variable: main');
return 'main';
}
else if (settings.pageTypeGTMnames.catalog && settings.pageTypeGTMnames.catalog.indexOf(settings.pageTypeGTM) !== -1) {
debug.log.call(this, 'Page type found by GTM variable: catalog');
return 'catalog';
}
if (settings.pageTypeGTM === settings.siteSearchPage) {
debug.log.call(this, 'Page type found by GTM variable: search');
return 'search';
}
else {
debug.log.call(this, 'Page type found by GTM variable: other');
return 'other';
}
}
else {
if (settings.mainPage && main.url.href.match(settings.mainPage) !== null) {
debug.log.call(this, 'Page type: main');
return 'main';
}
else if (settings.catalogPage && main.url.href.match(settings.catalogPage) !== null) {
debug.log.call(this, 'Page type: catalog');
return 'catalog';
}
else if (settings.siteSearchPage && main.url.href.match(settings.siteSearchPage) !== null) {
debug.log.call(this, 'Page type: search');
return 'search';
}
else {
debug.log.call(this, 'Page type: other');
return 'other';
}
}
},
/**
* Getting a site search query.
* @returns {string} Search query.
*/
getSiteSearchPhrase: function() {
debug.log_start.call(this, 'event.getSiteSearchPhrase');
if (settings.siteSearchQueryParam && this.getPageType() === 'search') {
var query = main.url.search.substring(1);
var vars = query.split('&');
var queryString = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (typeof queryString[pair[0]] === 'undefined') {
queryString[pair[0]] = decodeURIComponent(pair[1]);
}
else if (typeof queryString[pair[0]] === 'string') {
var arr = [queryString[pair[0]], decodeURIComponent(pair[1])];
queryString[pair[0]] = arr;
}
else {
queryString[pair[0]].push(decodeURIComponent(pair[1]));
}
}
for (var param in queryString) {
if (Array.isArray(queryString[param])) {
queryString[param] = queryString[param].join();
}
}
debug.log.call(this, 'Site search query:', queryString[settings.siteSearchQueryParam]);
return queryString[settings.siteSearchQueryParam];
}
else {
debug.log.call(this, 'Site search query not found');
}
}
},
// Page URL parameters
url: {
host: window.location.hostname,
search: window.location.search,
href: window.location.href
},
// Name of the object to display in the console when the debug mode is activated
debugName: 'system',
/**