-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathtagging.js
2505 lines (1989 loc) · 86.2 KB
/
tagging.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
var automationSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Automation Set-Up");
//var GTM_ACCOUNT_ID = automationSheet.getRange("B8").getValue();
var GTM_ACCOUNT_ID = '132607215'
var GTM_CONTAINER_SITE_ID = automationSheet.getRange("B10").getValue();
var GTM_CONTAINER_ID = automationSheet.getRange("B11").getValue();
//var GA_ACCOUNT_ID = automationSheet.getRange("B13").getValue();
var GA_ACCOUNT_ID = '62200884'
var GA_PROPERTY_ID = automationSheet.getRange("B14").getValue();
var DL_PREFIX = automationSheet.getRange("B17").getValue();
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createAddonMenu(); // Or DocumentApp or FormApp.
if (e && e.authMode == ScriptApp.AuthMode.NONE) {
// Add a normal menu item (works in all authorization modes).
menu.addItem('Approve GTM Access', 'aprroveGtmAccess');
menu.addItem('Restart Automation Set-up', 'restartAutomationSetup');
menu.addItem('Get GTM Containers', 'getGtmInfo');
menu.addItem('Get GA Properties', 'getGaInfo');
menu.addItem('Get dataLayer & GTM Code', 'getDlGtmCode');
menu.addItem('Set-Up dataLayer QA Tag in GTM', 'createQaTriggersTag');
menu.addItem('Set-Up GTM Triggers & Variables', 'setUpGtmVarsTriggers');
menu.addItem('Set-Up CDs / CMs in GA & GA Tags in GTM', 'setUpGtmGa');
menu.addItem('Set-Up Adometry Tags in GTM', 'createAllAdometryTagsInGtm');
menu.addItem('Get QA Tag', 'getQaTag');
} else {
menu.addItem('Approve GTM Access', 'aprroveGtmAccess');
menu.addItem('Restart Automation Set-up', 'restartAutomationSetup');
menu.addItem('Get GTM Containers', 'getGtmInfo');
menu.addItem('Get GA Properties', 'getGaInfo');
menu.addItem('Get dataLayer & GTM Code', 'getDlGtmCode');
menu.addItem('Set-Up dataLayer QA Tag in GTM', 'createQaTriggersTag');
menu.addItem('Set-Up GTM Triggers & Variables', 'setUpGtmVarsTriggers');
menu.addItem('Set-Up CDs / CMs in GA & GA Tags in GTM', 'setUpGtmGa');
menu.addItem('Set-Up Adometry Tags in GTM', 'createAllAdometryTagsInGtm');
menu.addItem('Get QA Tag', 'getQaTag');
// Add a menu item based on properties (doesn't work in AuthMode.NONE).
/*var properties = PropertiesService.getDocumentProperties();
var workflowStarted = properties.getProperty('workflowStarted');
if (workflowStarted) {
menu.addItem('Check workflow status', 'checkWorkflow');
} else {
menu.addItem('Start workflow', 'startWorkflow');
}*/
// Record analytics.
//UrlFetchApp.fetch('http://www.example.com/analytics?event=open');
}
menu.addToUi();
}
function aprroveGtmAccess(){
showGtmSidebar()
}
function restartAutomationSetup(){
automationSheet.getRange("B3").setValue('')
automationSheet.getRange("B3").setBackground('white')
automationSheet.getRange("B5").setValue('')
automationSheet.getRange("B5").setBackground('white')
automationSheet.getRange("B18").setValue('')
automationSheet.getRange("B18").setBackground('white')
automationSheet.getRange("B21").setValue('')
automationSheet.getRange("B21").setBackground('white')
automationSheet.getRange("B22").setValue('')
automationSheet.getRange("B22").setBackground('white')
automationSheet.getRange("B25").setValue('')
automationSheet.getRange("B25").setBackground('white')
getGtmAccountsRequest()
getGtmContainersRequest()
getGaProperties()
var output = '<p>You are now ready to start the automation process again</p>';
var htmlOutput = HtmlService
.createHtmlOutput( output )
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(650)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Restart Automation Set-up');
}
function getGtmInfo(){
getGtmAccountsRequest()
getGtmContainersRequest()
}
function getGaInfo(){
getGaProperties()
//getGaCustomDimensions()
//getGaCustomMetrics()
}
function getDlGtmCode(){
createDataLayerCode()
}
function createQaTriggersTag(){
createAllPagesDebugTrigger();
createAllEventsDebugTrigger();
createGtmVariablesDataLayerIndexed();
createQaTagInGtm();
automationSheet.getRange("B21").setValue('DONE - ' + new Date() )
automationSheet.getRange("B21").setBackground('#6aa84f')
var output = '<p>Enable Preview Mode in GTM to see dataLayer QA results in the console.</p><p>Enable persist mode in the console to see your results for events.</p><p>Copy and paste the results into the tab "dataLayer QA"</p>';
var htmlOutput = HtmlService
.createHtmlOutput( output )
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(650)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Set-Up QA DataLayer Tag in GTM Complete');
}
function setUpGtmVarsTriggers(){
createGtmVariablesFromDataLayer()
createGtmTriggersFromDataLayer()
automationSheet.getRange("B25").setValue('DONE - ' + new Date() )
automationSheet.getRange("B25").setBackground('#6aa84f')
}
function setUpGtmGa(){
createAllGoogleAnalyticsTagsInGtm()
}
function getQaTag(){
}
function getGaAccounts() {
var accounts = Analytics.Management.Accounts.list();
var accountsObj = {}
if (accounts.items && accounts.items.length) {
for (var i = 0; i < accounts.items.length; i++) {
var account = accounts.items[i];
accountsObj[account.id] = account
//Logger.log(JSON.stringify(account))
//Logger.log('Account: name "%s", id "%s".', account.name, account.id);
// List web properties in the account.
// listWebProperties(account.id);
}
} else {
Logger.log('No accounts found.');
}
return accountsObj
}
function getGaProperties() {
var accounts = getGaAccounts()
//Logger.log(accounts)
var properties = Analytics.Management.Webproperties.list('~all')
var accountsProperties = []
if (properties.items && properties.items.length) {
for (var i = 0; i < properties.items.length; i++) {
var property = properties.items[i];
property.accountName = [accounts[property.accountId].name]
accountsProperties.push([property.accountName, property.accountId, property.name, property.id, property.level, property.accountName + ' - ' + property.name])
//Logger.log(JSON.stringify(property))
//Logger.log('Account: name "%s", id "%s".', account.name, account.id);
// List web properties in the account.
// listWebProperties(account.id);
}
Logger.log(accountsProperties.length)
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GA Properties");
//getRange(row, column, numRows, numColumns)
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
sheet.getRange(2, 1, lastRow, 6).clear();
sheet.getRange(2, 1, accountsProperties.length, 6).setValues(accountsProperties);
var output = '<p>' + accountsProperties.length +
' Google Analytics Properties retrieved.</p>' +
'<p>Select the property you want to set-up in the dropdown in the <strong>Automation Set-Up</strong> tab.</p>';
var htmlOutput = HtmlService
.createHtmlOutput( output )
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(650)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Containers List Refresh Complete');
automationSheet.getRange("B5").setValue('DONE - ' + new Date() )
automationSheet.getRange("B5").setBackground('#6aa84f')
} else {
Logger.log('No accounts found.');
}
}
function getGaCdIndexedObject(){
Logger.log(JSON.stringify(getGaCustomDimensions('indexedObject')))
}
function getGaCustomDimensions(usageType) {
var usageType = !!usageType ? usageType : 'default'
var dimensions = Analytics.Management.CustomDimensions.list(GA_ACCOUNT_ID, GA_PROPERTY_ID)
var dimensionsIndexedObj = {}
//Logger.log(usageType)
/*
{"scope":"HIT",
"id":"ga:dimension1",
"parentLink":{"href":"https://www.googleapis.com/analytics/v3/management/accounts/62200884/webproperties/UA-62200884-1",
"type":"analytics#webproperty"},
"kind":"analytics#customDimension",
"created":"2015-09-27T16:29:29.828Z",
"index":1,
"active":true,
"webPropertyId":"UA-62200884-1",
"selfLink":"https://www.googleapis.com/analytics/v3/management/accounts/62200884/webproperties/UA-62200884-1/customDimensions/ga:dimension1",
"accountId":"62200884",
"name":"Page Type","updated":"2015-09-27T16:29:29.828Z"}
*/
if (dimensions.items && dimensions.items.length) {
var dimensionsValues = dimensions.items.map(function(obj){
//Logger.log(JSON.stringify(obj))
dimensionsIndexedObj[obj.name+'-'+obj.scope] = obj
return [obj.accountId, obj.webPropertyId, obj.id, obj.index, obj.name, obj.scope, obj.active];
});
if (usageType == 'default'){
//Logger.log(dimensionsValues)
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GA Dimensions");
//getRange(row, column, numRows, numColumns)
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
sheet.getRange(2, 1, lastRow, dimensionsValues[0].length).clear();
sheet.getRange(2, 1, dimensionsValues.length, dimensionsValues[0].length).setValues(dimensionsValues);
} else if (usageType == 'indexedObject'){
//Logger.log('dimensionsIndexedObj')
return dimensionsIndexedObj
}
} else {
return {};
//Logger.log('No custom dimensions found.');
}
}
function createGaCustomDimension(name,scope,active){
var newDimension = Analytics.newCustomDimension();
newDimension.name = name;
newDimension.scope = scope;
newDimension.active = active;
var dimensions = Analytics.Management.CustomDimensions.insert(newDimension, GA_ACCOUNT_ID, GA_PROPERTY_ID)
//Logger.log(dimensions.index)
return dimensions.index
}
function getGaCustomMetrics(usageType) {
var usageType = !!usageType ? usageType : 'default'
var metrics = Analytics.Management.CustomMetrics.list(GA_ACCOUNT_ID, GA_PROPERTY_ID)
var metricsIndexedObj = {}
/*
"type":"CURRENCY",
"scope":"PRODUCT",
"id":"ga:metric1",
"parentLink":{"href":"https://www.googleapis.com/analytics/v3/management/accounts/62200884/webproperties/UA-62200884-1","type":"analytics#webproperty"},
"kind":"analytics#customMetric",
"created":"2015-09-27T17:01:16.538Z",
"index":1,
"active":true,
"webPropertyId":"UA-62200884-1",
"selfLink":"https://www.googleapis.com/analytics/v3/management/accounts/62200884/webproperties/UA-62200884-1/customMetrics/ga:metric1",
"accountId":"62200884",
"name":"Produc Sale Price",
"updated":"2015-09-27T17:01:34.677Z"}
*/
if (metrics.items && metrics.items.length) {
var metricsValues = metrics.items.map(function(obj){
//Logger.log(JSON.stringify(obj))
metricsIndexedObj[obj.name+'-'+obj.scope+'-'+obj.type] = obj
return [obj.accountId, obj.webPropertyId, obj.id, obj.index, obj.name, obj.scope, obj.type, obj.active];
});
if (usageType == 'default'){
//Logger.log(metricsValues)
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GA Metrics");
//getRange(row, column, numRows, numColumns)
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
sheet.getRange(2, 1, lastRow, metricsValues[0].length).clear();
sheet.getRange(2, 1, metricsValues.length, metricsValues[0].length).setValues(metricsValues);
} else if (usageType == 'indexedObject'){
//Logger.log('metricsIndexedObj')
return metricsIndexedObj
}
} else {
if (usageType == 'default'){
//getRange(row, column, numRows, numColumns)
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
sheet.getRange(2, 1, lastRow, metricsValues[0].length).clear();
sheet.getRange(2, 1, 1, 1).setValues([['No custom metrics found.']]);
Logger.log('No custom metrics found.');
} else {
return {'message':'No custom metrics found'}
}
}
}
function createGaCustomMetric(name,scope,type,active){
var newMetric = Analytics.newCustomMetric()
Logger.log(name)
Logger.log(scope)
Logger.log(type)
Logger.log(active)
newMetric.name = name;
newMetric.scope = scope;
newMetric.type = type;
newMetric.active = active;
var metrics = Analytics.Management.CustomMetrics.insert(newMetric, GA_ACCOUNT_ID, GA_PROPERTY_ID)
//Logger.log(metrics.index)
return metrics.index
}
// Connect To GTM API
// File > Project Properties
// Project key: MMRYe9YCsHP9e0PIf2BV-WE9pAQWesLUp
// Callback > https://pantheon.corp.google.com/project/360489325281/apiui/credential
// https://script.google.com/macros/d/{PROJECT KEY}/usercallback
// https://script.google.com/macros/d/MMRYe9YCsHP9e0PIf2BV-WE9pAQWesLUp/usercallback
// Client ID
// 360489325281-k6p8jl7b2cmsufohntu3n70cp0ic62t1.apps.googleusercontent.com
// Client secret
// iihR_JQhfPtuY8URzr0TsobU
// Creation date
// Sep 14, 2015, 9:23:23 PM
function getGtmService() {
// via https://github.com/googlesamples/apps-script-oauth2
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('gtm_wizard')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId('360489325281-k6p8jl7b2cmsufohntu3n70cp0ic62t1.apps.googleusercontent.com')
.setClientSecret('iihR_JQhfPtuY8URzr0TsobU')
// Set the project key of the script using this library.
// You can find your script's project key in the Apps Script code editor by clicking on the menu item "File > Project properties".
.setProjectKey('MMRYe9YCsHP9e0PIf2BV-WE9pAQWesLUp')
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
.setScope('https://www.googleapis.com/auth/tagmanager.edit.containers')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getActiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
function showGtmSidebar() {
var gtmService = getGtmService();
Logger.log(gtmService)
if (!gtmService.hasAccess()) {
var authorizationUrl = gtmService.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
SpreadsheetApp.getUi().showSidebar(page);
} else {
Logger.log('GTM ACCESS OK')
}
}
function authCallback(request) {
var gtmService = getGtmService();
var isAuthorized = gtmService.handleCallback(request);
if (isAuthorized) {
automationSheet.getRange("B2").setValue('DONE - ' + new Date() )
automationSheet.getRange("B2").setBackground('#6aa84f')
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
function getGtmAccountsRequest() {
var gtmService = getGtmService();
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts', {
headers: {
Authorization: 'Bearer ' + gtmService.getAccessToken()
}
});
//Logger.log(JSON.parse(response.getContentText()))
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GTM Accounts");
var accountsObj = {}
var response = JSON.parse(response.getContentText())
var accounts = response.accounts.map(function(obj){
accountsObj[obj.accountId] = obj
return [obj.accountId, obj.name];
});
//Logger.log(accounts)
//Logger.log(accounts.length)
//for (var i = 0; i < accounts.length; i++){
//sheet.appendRow(accounts[i]);
//}
//getRange(row, column, numRows, numColumns)
sheet.getRange(2, 1, accounts.length, 2).setValues(accounts);
return response.accounts
}
function getGtmContainersRequest() {
var gtmService = getGtmService();
var accounts = getGtmAccountsRequest()
var accountsObj = {}
var accounts = accounts.map(function(obj){
accountsObj[obj.accountId] = obj
return obj
});
//Logger.log(JSON.stringify(accountsObj, null, 2))
var containersValues = []
for (var i = 0; i < accounts.length; i++){
//var accountId = GTM_ACCOUNT_ID
var accountId = accounts[i].accountId
var accountName = accountsObj[accounts[i].accountId].name
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers', {
headers: {
Authorization: 'Bearer ' + gtmService.getAccessToken()
}
});
Logger.log(JSON.parse(response.getContentText()))
var response = JSON.parse(response.getContentText())
var containers = response.containers.map(function(obj){
containersValues.push([accountName, obj.accountId, obj.containerId, obj.publicId, obj.name, accountName + ' - ' + obj.name])
return [accountName, obj.accountId, obj.containerId, obj.publicId, obj.name, accountName + ' - ' + obj.name];
});
//Logger.log(containers[0])
}
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GTM Containers");
//getRange(row, column, numRows, numColumns)
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
sheet.getRange(2, 1, lastRow, containersValues[0].length).clear();
sheet.getRange(2, 1, containersValues.length, containersValues[0].length).setValues(containersValues);
var output = '<p>' + containersValues.length +
' GTM containers retrieved.</p>' +
'<p>Select the container you want to set-up in the dropdown in the <strong>Automation Set-Up</strong> tab.</p>';
var htmlOutput = HtmlService
.createHtmlOutput( output )
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(650)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Containers List Refresh Complete');
automationSheet.getRange("B3").setValue('DONE - ' + new Date() )
automationSheet.getRange("B3").setBackground('#6aa84f')
}
function getGtmVariablesRequest() {
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/variables', {
headers: {
Authorization: 'Bearer ' + gtmService.getAccessToken()
}
});
Logger.log(JSON.parse(response.getContentText()))
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GTM variables");
var response = JSON.parse(response.getContentText())
if (!!response.variables){
var variables = response.variables.map(function(obj){
return [obj.accountId, obj.containerId, obj.variableId, obj.name, '{{'+obj.name+'}}', obj.parameter[0].value, obj.type, JSON.stringify(obj.parameter)];
});
Logger.log(variables[0])
/*for (var i = 0; i < variables.length; i++){
sheet.appendRow(variables[i]);
}*/
//getRange(row, column, numRows, numColumns)
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
sheet.getRange(2, 1, lastRow, lastColumn).clear();
sheet.getRange(2, 1, variables.length, 8).setValues(variables);
}
}
function createGtmVariablesFromDataLayer() {
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("dataLayer");
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
// getRange(row, column, numRows, numColumns)
var range = sheet.getRange(1, 1, lastRow, lastColumn);
var values = range.getValues();
//Logger.log(values)
/* Modify this to create all the dataLayer keys based on what is actually being used and taking into account the new replace option
for (var i = 3; i < values.length; i++) {
var key = values[i][0]
var value = values[i][k]
var keyReplaceRegex = /\<(.*?)\>/;
if(keyReplaceRegex.test(value)) {
var matches = value.match(keyReplaceRegex);
//console.log(matches)
var key = key.split('<replace>').join(matches[1])
var value = value.split('|')[0]
} else {
var key = key
var value = value.split('|')[0]
}
if(value.indexOf('REQ -') > -1 || value.indexOf('OPT -') > -1 ){
flatObjectArr[k - 3][key] = values[i][1] + ' - ' + value
} else if(values[i][k] != ''){
flatObjectArr[k - 3][key] = value
}
}*/
for (var i = 0; i < values.length; i++) {
var dataLayerKeyName = values[i][0];
var dataLayerKeyType = values[i][1];
if ((dataLayerKeyType === 'STRING' || dataLayerKeyType === 'NUMBER') && dataLayerKeyName !== 'event'){
Logger.log(dataLayerKeyName + ' - ' + values[i][0])
var data =
{
'name': DL_PREFIX + ' - ' + dataLayerKeyName,
'type': 'v',
'parameter': [{"type":"template","key":"name","value":dataLayerKeyName},{"type":"integer","key":"dataLayerVersion","value":"2"}]
};
var payload = JSON.stringify(data);
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options =
{ "contentType" : "application/json",
"muteHttpExceptions" : true,
"method" : "post",
"headers" : {
Authorization: 'Bearer ' + gtmService.getAccessToken()
},
"payload" : payload
};
try {
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/variables', options);
Logger.log(JSON.parse(response.getContentText()))
}
catch (e) {
// statements to handle any exceptions
Logger.log(e); // pass exception object to error handler
}
}
}
getGtmVariablesRequest()
}
function createGtmTriggersFromDataLayer(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("dataLayer");
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn()
// getRange(row, column, numRows, numColumns)
var range = sheet.getRange(1, 4, 2, lastColumn-3);
var values = range.getValues();
for (var i = 0; i < values[0].length; i++){
var triggerType = values[0][i] == 'pageload' ? 'page.type' : 'event'
var triggerKey;
var triggerValue = values[1][i]
var triggerName = triggerType + ' equals ' + triggerValue
Logger.log(triggerName)
if (triggerType == 'page.type'){
triggerKey = '{{'+DL_PREFIX+' - page.type}}'
// create pageview trigger
createPageviewTrigger(triggerName,triggerKey,triggerValue)
} else {
// create event trigger
createEventTrigger(triggerName,triggerValue)
}
}
Logger.log(values)
}
function createPageviewTrigger(name,key,value){
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var key = !!key ? key : '{{dataLayer - test.key}}';
var value = !!value ? value : 'test ' + new Date().getTime();
var name = !!name ? name : DL_PREFIX+' - page.type equals ' + value;
var data =
{
'name': name,
'type': 'pageview',
'filter': [
{
'type': 'equals',
'parameter': [
{
'type': 'template',
'key': 'arg0',
'value': key
},
{
'type': 'template',
'key': 'arg1',
'value': value
}
]
}
]
};
var payload = JSON.stringify(data);
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options =
{ "contentType" : "application/json",
"muteHttpExceptions" : true,
"method" : "post",
"headers" : {
Authorization: 'Bearer ' + gtmService.getAccessToken()
},
"payload" : payload
};
try {
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/triggers', options);
Logger.log(JSON.parse(response.getContentText()))
}
catch (e) {
// statements to handle any exceptions
Logger.log(e); // pass exception object to error handler
}
}
function createEventTrigger(triggerName,eventName){
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var eventName = !!eventName ? eventName : 'testEventName ' + new Date().getTime();
var triggerName = !!triggerName ? triggerName : 'event ' + eventName;
var data =
{
'name': triggerName,
'type': 'customEvent',
'customEventFilter': [
{
'type': 'equals',
'parameter': [
{
'type': 'template',
'key': 'arg0',
'value': '{{_event}}'
},
{
'type': 'template',
'key': 'arg1',
'value': eventName
}
]
}
]
};
var payload = JSON.stringify(data);
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options =
{ "contentType" : "application/json",
"muteHttpExceptions" : true,
"method" : "post",
"headers" : {
Authorization: 'Bearer ' + gtmService.getAccessToken()
},
"payload" : payload
};
try {
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/triggers', options);
Logger.log(JSON.parse(response.getContentText()))
}
catch (e) {
// statements to handle any exceptions
Logger.log(e); // pass exception object to error handler
}
}
function deleteAllTriggers(){
var triggersLength = getGtmTriggersRequest().triggers.length
for (var i = 0; i < triggersLength; i++){
deleteTrigger(i+1)
}
}
function deleteTrigger(triggerId){
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var triggerId = !!triggerId ? triggerId.toString() : '1';
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options =
{ "contentType" : "application/json",
"muteHttpExceptions" : true,
"method" : "delete",
"headers" : {
Authorization: 'Bearer ' + gtmService.getAccessToken()
}
};
try {
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/triggers/'+triggerId, options);
Logger.log(JSON.parse(response.getContentText()))
}
catch (e) {
// statements to handle any exceptions
Logger.log(e); // pass exception object to error handler
}
}
function getGtmTriggersRequest() {
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/triggers', {
headers: {
Authorization: 'Bearer ' + gtmService.getAccessToken()
}
});
Logger.log(JSON.parse(response.getContentText()))
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GTM Triggers");
var response = JSON.parse(response.getContentText())
var triggers = response.triggers.map(function(obj){
return [obj.accountId, obj.containerId, obj.triggerId, obj.name, JSON.stringify(obj.filter)];
});
Logger.log(triggers[0])
//for (var i = 0; i < containers.length; i++){
//sheet.appendRow(containers[i]);
//}
//getRange(row, column, numRows, numColumns)
sheet.getRange(2, 1, triggers.length, 5).setValues(triggers);
return response
}
function getGtmTagsRequest() {
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/tags', {
headers: {
Authorization: 'Bearer ' + gtmService.getAccessToken()
}
});
Logger.log(JSON.parse(response.getContentText()))
return response
}
function createTagBasicUniversalAnalytics(){
var gtmService = getGtmService();
var accountId = GTM_ACCOUNT_ID;
var containerId = GTM_CONTAINER_ID;
var data = {
"name": "Universal Analytics - All Pages",
"type": "ua",
"blockingTriggerId":[],
"liveOnly": false,
"parameter": [
{
"type": "template",
"key": "trackingId",
"value": "UA-12345678-9"
},
{
"type": "template",
"key": "trackType",
"value": "TRACK_PAGEVIEW"
}
]
}
var payload = JSON.stringify(data);
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options =
{ "contentType" : "application/json",
"muteHttpExceptions" : true,
"method" : "post",
"headers" : {
Authorization: 'Bearer ' + gtmService.getAccessToken()
},
"payload" : payload
};
try {
var response = UrlFetchApp.fetch('https://www.googleapis.com/tagmanager/v1/accounts/'+accountId+'/containers/'+containerId+'/tags', options);
Logger.log(JSON.parse(response.getContentText()))
}
catch (e) {
// statements to handle any exceptions
Logger.log(e); // pass exception object to error handler
}
}
function getTriggersLookupObject(){
var triggersList = getGtmTriggersRequest().triggers;
var triggerObj = {}
for (var i = 0; i < triggersList.length; i++){
triggerObj[triggersList[i].name] = {triggerId: triggersList[i].triggerId}
}
//Logger.log(triggersList)