lpw
2025-03-18 bcf5da418199cecd2968f2f8bf2974c8dcc6e283
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
/**
 * Initialize the SDK with the specified configuration
 */
function initSdk(config, gvl, sdkURL, languageCode) {
  if (config) {
    // Set the global window configuration to the config object
    window.didomiConfig = prepareConfigFromMobile(config, languageCode);
 
    // If app, vendors, and iab exist, set the vendorList property
    if (
      window.didomiConfig.app &&
      window.didomiConfig.app.vendors &&
      window.didomiConfig.app.vendors.iab
    ) {
      window.didomiConfig.app.vendors.iab.vendorList = prepareGVLFromMobile(gvl);
    }
  }
 
  var script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.setAttribute("src", sdkURL);
 
  document.getElementsByTagName("head")[0].appendChild(script);
 
  addReadyHandler();
  addErrorHandler();
}
 
// Used to trigger a "ready" message when the Web SDK is ready.
function addReadyHandler() {
  window.didomiOnReady = window.didomiOnReady || [];
  window.didomiOnReady.push(function () {
    if (isIOS()) {
      window.webkit.messageHandlers.ready.postMessage("");
    }
  });
}
 
// Used to detect when there's an error loading files so native can dismiss the notice if required.
function addErrorHandler() {
  window.addEventListener('error', function(event) {
    if (event.target.tagName === 'IMG' || event.target.tagName === 'SCRIPT' || event.target.tagName === 'LINK') {
      const errorObject = {
        url: event.target.src || event.target.href,
        tagName: event.target.tagName,
        errorMessage: event.message || "Resource failed to load"
      };
      if (isIOS()) {
        window.webkit.messageHandlers.errorLoadingResource.postMessage(errorObject);
      } else {
        androidInterface.onErrorLoadingResource(JSON.stringify(errorObject));
      }
    }
  }, true);
}
 
/**
 * Open the notice screen
 */
function openNotice(options) {
  window.didomiOnReady = window.didomiOnReady || [];
  window.didomiOnReady.push(function (Didomi) {
    if (options != null && options.deepLinkView != null) {
      Didomi.preferences.show(
        options.deepLinkView == 0 ? "purposes" : "vendors"
      );
    } else {
      Didomi.notice.show();
    }
  });
 
  window.didomiEventListeners = window.didomiEventListeners || [];
  // TODO: Handle all iOS events
  window.didomiEventListeners.push(
    {
      event: 'api.error',
      listener: function ({ id, reason }) {
        if (window.webkit && window.webkit.messageHandlers) {
          window.webkit.messageHandlers.onError.postMessage(reason);
        } else {
          androidInterface.onError(id, reason);
        }
      }
    },
    {
      event: "consent.changed",
      listener: function (event) {
        // If the change is coming from the WebView we don't want to trigger the message back to the WebView.
        if (event.action == "webview") {
          return;
        }
 
        if (isIOS()) {
          window.webkit.messageHandlers.consentChanged.postMessage(Didomi.getUserStatus());
        } else {
          androidInterface.onConsentChanged(JSON.stringify(Didomi.getUserStatus()));
        }
      },
    },
    {
      event: 'notice.clickagree',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.noticeClickAgree.postMessage("");
        } else {
          androidInterface.onNoticeClickAgree();
        }
      }
    },
    {
      event: 'notice.clickdisagree',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.noticeClickDisagree.postMessage("");
        } else {
          androidInterface.onNoticeClickDisagree();
        }
      }
    },
    {
      event: 'notice.clickmoreinfo',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.noticeClickMoreInfo.postMessage("");
        } else {
          androidInterface.onNoticeClickMoreInfo();
        }
      }
    },
    {
      event: 'notice.clickviewvendors',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.noticeClickViewVendors.postMessage("");
        } else {
          androidInterface.onNoticeClickViewVendors();
        }
      }
    },
    {
      event: 'notice.hidden',
      listener: function () {
        if (isIOS()) {
          if (Didomi.notice.isVisible()) {
            window.webkit.messageHandlers.noticeHidden.postMessage();
          }
        } else {
          androidInterface.onNoticeHidden();
        }
      }
    },
    {
      event: 'notice.shown',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.noticeShown.postMessage("");
        } else {
          androidInterface.onNoticeShown();
        }
      }
    },
    {
      event: 'preferences.clickagreetoall',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickAgreeToAll.postMessage("");
        } else {
          androidInterface.onPreferencesClickAgreeToAll();
        }
      }
    },
    {
      event: 'preferences.clickcategoryagree',
      listener: function ({ categoryId }) {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickCategoryAgree.postMessage(categoryId);
        } else {
          androidInterface.onPreferencesClickCategoryAgree(categoryId);
        }
      }
    },
    {
      event: 'preferences.clickcategorydisagree',
      listener: function ({ categoryId }) {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickCategoryDisagree.postMessage(categoryId);
        } else {
          androidInterface.onPreferencesClickCategoryDisagree(categoryId);
        }
      }
    },
    {
      event: "preferences.clickclose",
      listener: function () {
        // Not handled by mobile SDKs
      },
    },
    {
      event: 'preferences.clickdisagreetoall',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickDisagreeToAll.postMessage("");
        } else {
          androidInterface.onPreferencesClickDisagreeToAll();
        }
      }
    },
    {
      event: 'preferences.clickpurposeagree',
      listener: function ({ purposeId }) {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickPurposeAgree.postMessage(purposeId);
        } else {
          androidInterface.onPreferencesClickPurposeAgree(purposeId);
        }
      }
    },
    {
      event: 'preferences.clickpurposedisagree',
      listener: function ({ purposeId }) {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickPurposeDisagree.postMessage(purposeId);
        } else {
          androidInterface.onPreferencesClickPurposeDisagree(purposeId);
        }
      }
    },
    {
      event: 'preferences.clicksavechoices',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickSaveChoices.postMessage("");
        } else {
          androidInterface.onPreferencesClickSaveChoices();
        }
      }
    },
    {
      event: 'preferences.clickvendoragree',
      listener: function ({ vendorId }) {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickVendorAgree.postMessage(vendorId);
        } else {
          androidInterface.onPreferencesClickVendorAgree(vendorId);
        }
      }
    },
    {
      event: 'preferences.clickvendordisagree',
      listener: function ({ vendorId }) {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickVendorDisagree.postMessage(vendorId);
        } else {
          androidInterface.onPreferencesClickVendorDisagree(vendorId);
        }
      }
    },
    {
      event: 'preferences.clickvendorsavechoices',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickVendorSaveChoices.postMessage("");
        } else {
          androidInterface.onPreferencesClickVendorSaveChoices();
        }
      }
    },
    {
      event: 'preferences.clickviewvendors',
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesClickViewVendors.postMessage("");
        } else {
          androidInterface.onPreferencesClickViewVendors();
        }
      }
    },
    {
      event: "preferences.hidden",
      listener: function () {
        if (Didomi.notice.isVisible()) {
          if (isIOS()) {
            window.webkit.messageHandlers.preferencesHidden.postMessage("");
          } else {
            androidInterface.onPreferencesHidden();
          }
        } else {
          if (isIOS()) {
            window.webkit.messageHandlers.dismissWebView.postMessage("");
          } else {
            androidInterface.onDismissPreferences();
          }
        }
      }
    },
    {
      event: "preferences.shown",
      listener: function () {
        if (isIOS()) {
          window.webkit.messageHandlers.preferencesShown.postMessage("");
        } else {
          androidInterface.onPreferencesShown();
        }
      }
    },
  );
}
 
/**
 * Show the Preferences screen programmatically after the notice was already opened
 */
function showPreferences() {
  window.didomiOnReady = window.didomiOnReady || [];
  window.didomiOnReady.push(function (Didomi) {
    Didomi.preferences.show();
  });
}
 
/**
 * Click on the 1st visible slider button if it exists.
 * Used to cache both states of the slider button.
 */
function toggleFirstSlider() {
  new Promise(function(resolve) {
    setTimeout(() => {  // Add delay to let time for the element to be attached
      var element = document.getElementsByClassName('didomi-switch')[0];
      if (element) {
        element.click();
        resolve(true);
      } else {
        resolve(false);
      }
    }, 100);
  }).then((result) => {
      enabledToggleIsCachedOrNotRequired(result);
  });
}
 
/**
 * If the preferences page shows toggles, we let the native code know that the enable toggle image should be loaded on the page and cached now.
 * If the preferences page does not show toggles, we also let native know that we can continue.
 * @param {*} result whether the toggle has been found and clicked or not.
 */
function enabledToggleIsCachedOrNotRequired(result) {
  if (isIOS()) {
    window.webkit.messageHandlers.enabledToggleIsCached.postMessage("");
  } else if (!result) {
    androidInterface.onSliderNotPresent();
  }
}
 
/**
 * Hide the Preferences screen programmatically
 */
function hidePreferences() {
  window.didomiOnReady = window.didomiOnReady || [];
  window.didomiOnReady.push(function (Didomi) {
    Didomi.preferences.hide();
  });
}
 
/**
 * Hide the Vendors screen programmatically
 */
function hideVendors() {
  // preferences.show() command will display the purposes screen with no changes in user choices
  showPreferences();
}
 
/**
 * Function used to convert objects that are mapped by ID into an array of objects that only contain IDs.
 * @param {*} object JSON object.
 * @returns array of objects that only contain an ID.
 */
function convertObjectToArrayWithIDs(object) {
  if (!object) {
    return [];
  }
  return Object.keys(object).map(function (id) {
    return {
      id: Number(id),
    };
  });
}
 
/**
 * Remove all accents and special characters from id field
 * @param {string} id 
 * @returns the sanitized id
 */
function sanitizeID(id) {
  return id
    // Remove accents and diacritics
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    // Remove special characters
    .replace(/[^a-zA-Z0-9_-]/g, '');
}
 
/**
 * Fix unescaped quotes and html tags.
 * @param {string} text
 * @returns the sanitized text
 */
function sanitizeText(text) {
  return text
    // Escape unescaped quotes
    .replace(/(?<!\\)(['"])/g, '\$1')
    // Remove html tags
    .replace(/[<>]/g, '');
}
 
/**
 * Function used to sanitize custom fields in config.
 * @param {*} jsonConfig
 * @returns the sanitized config
 */
function sanitizeConfig(jsonConfig) {
  const resultJson = JSON.parse(JSON.stringify(jsonConfig));
 
  if (resultJson && resultJson.app) {
    if(resultJson.app.vendors && resultJson.app.vendors.custom && Array.isArray(resultJson.app.vendors.custom)) {
      resultJson.app.vendors.custom = resultJson.app.vendors.custom.map(vendor => {
          if (vendor.id) {
              vendor.id = sanitizeID(vendor.id);
          }
          if (vendor.purposeIds) {
            vendor.purposeIds = vendor.purposeIds.map(purposeID => sanitizeID(purposeID));
          }
          if (vendor.legIntPurposeIds) {
            vendor.legIntPurposeIds = vendor.legIntPurposeIds.map(purposeID => sanitizeID(purposeID));
          }
          if (vendor.name) {
            vendor.name = sanitizeText(vendor.name);
          }
          return vendor;
      });
    }
 
    if (resultJson.app.customPurposes) {
      resultJson.app.customPurposes = resultJson.app.customPurposes.map(purpose => {
        if (purpose.id) {
          purpose.id = sanitizeID(purpose.id);
        }
        if (purpose.name) {
          for (const key in purpose.name) {
            if (purpose.name.hasOwnProperty(key)) {
              purpose.name[key] = sanitizeText(purpose.name[key]);
            }
          }
        }
        if (purpose.description) {
          for (const key in purpose.description) {
            if (purpose.description.hasOwnProperty(key)) {
              purpose.description[key] = sanitizeText(purpose.description[key]);
            }
          }
        }
        if (purpose.descriptionLegal) {
          for (const key in purpose.descriptionLegal) {
            if (purpose.descriptionLegal.hasOwnProperty(key)) {
              purpose.descriptionLegal[key] = sanitizeText(purpose.descriptionLegal[key]);
            }
          }
        }
        return purpose;
      });
    }
  }
 
  return resultJson;
}
 
/**
 * Check if the platform is iOS.
 * @returns true if the platform is iOS, false otherwise.
 */
function isIOS() {
  return window.webkit != null && window.webkit.messageHandlers != null;
}
 
/**
 * Prepare config file to be consumed by the Web SDK, by disabling the features already handled by Mobile SDKs.
 * @param {*} configFromMobile Config provided by mobile.
 * @param {string} languageCode language code to be set in the Config.
 * @returns Config with unneeded features disabled
 */
function prepareConfigFromMobile(configFromMobile, languageCode) {
  if (configFromMobile == null) {
    return null;
  }
 
  configFromMobile = sanitizeConfig(configFromMobile);
 
  // If the `events` object is not defined, we define it and make sure the enabled property is set to `false`.
  configFromMobile.events = configFromMobile.events || {};
  configFromMobile.events.enabled = false;
 
  if (configFromMobile.sync) {
    configFromMobile.sync.enabled = false;
  }
 
  if (configFromMobile.app && configFromMobile.app.consentString) {
    configFromMobile.app.consentString.signatureEnabled = false;
  }
 
  if (languageCode) {
    configFromMobile.languages = { enabled: [languageCode], default: languageCode };
  }
 
  return configFromMobile;
}
 
/**
 * Prepare GVL to be consumed by the Web SDK based on the format used by Mobile SDKs.
 * @param {*} gvlFromMobile GVL in the format used by mobile.
 * @returns GVL in the format used by web.
 */
function prepareGVLFromMobile(gvlFromMobile) {
  if (gvlFromMobile == null) {
    return null;
  }
 
  gvlFromMobile.purposes = convertObjectToArrayWithIDs(gvlFromMobile.purposes);
  gvlFromMobile.specialPurposes = convertObjectToArrayWithIDs(gvlFromMobile.specialPurposes);
  gvlFromMobile.features = convertObjectToArrayWithIDs(gvlFromMobile.features);
  gvlFromMobile.specialFeatures = convertObjectToArrayWithIDs(gvlFromMobile.specialFeatures);
  gvlFromMobile.dataCategories = convertObjectToArrayWithIDs(gvlFromMobile.dataCategories);
 
  gvlFromMobile.stacks = Object.keys(gvlFromMobile.stacks).map(function (key) {
    var stack = gvlFromMobile.stacks[key];
    return {
      id: stack.id,
      purposeIds: stack.purposes || [],
      specialFeatureIds: stack.specialFeatures || [],
    };
  });
 
  gvlFromMobile.vendors = Object.keys(gvlFromMobile.vendors).map(function (key) {
    var vendor = gvlFromMobile.vendors[key];
    var {
      purposes,
      flexiblePurposes,
      specialPurposes,
      legIntPurposes,
      features,
      specialFeatures,
      ...rest
    } = vendor;
  
    return {
      ...rest,
      purposeIds: purposes || [],
      flexiblePurposeIds: flexiblePurposes || [],
      specialPurposeIds: specialPurposes || [],
      legIntPurposeIds: legIntPurposes || [],
      featureIds: features || [],
      specialFeatureIds: specialFeatures || [],
      tmpDeletedDate: rest.deletedDate,
    };
  });
  return gvlFromMobile;
}