tracardi-1.0.x-dev/js/tracardi.js
js/tracardi.js
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.tracardi = {
attach: function (context) {
if (drupalSettings.tracardi.enable_script) {
window.options = {
listeners: {},
tracker: {
url: {
script: drupalSettings.tracardi.api_url + '/tracker',
api: drupalSettings.tracardi.api_url
},
source: {
id: drupalSettings.tracardi.source_id
}
}
}
!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).tracardi=e()}(function(){return function n(o,i,a){function c(t,e){if(!i[t]){if(!o[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(d)return d(t,!0);throw(r=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",r}r=i[t]={exports:{}},o[t][0].call(r.exports,function(e){return c(o[t][1][e]||e)},r,r.exports,n,o,i,a)}return i[t].exports}for(var d="function"==typeof require&&require,e=0;e<a.length;e++)c(a[e]);return c}({1:[function(e,t,r){"use strict";!function(e){e=e||window;var r=[],n=!1,o=!1;function i(){if(!n){n=!0;for(var e=0;e<r.length;e++)r[e].fn.call(window,r[e].ctx);r=[]}}function a(){"complete"===document.readyState&&i()}e.documentReady=function(e,t){if("function"!=typeof e)throw new TypeError("callback for documentReady(fn) must be a function");n?setTimeout(function(){e(t)},1):(r.push({fn:e,ctx:t}),"complete"===document.readyState||!document.attachEvent&&"interactive"===document.readyState?setTimeout(i,1):o||(document.addEventListener?(document.addEventListener("DOMContentLoaded",i,!1),window.addEventListener("load",i,!1)):(document.attachEvent("onreadystatechange",a),window.attachEvent("onload",i)),o=!0))}}(window),window.tracker||(window.tracker={}),window.response||(window.response={context:{}}),function(){for(var r=[],n="liliput.min.js",e=["track"],t=0;t<e.length;t++){var o=e[t];window.tracker[o]=function(t){return function(){var e=Array.prototype.slice.call(arguments);return e.unshift(t),r.push(e),window.tracker}}(o)}function i(){if(console.debug("[Tracker] Rerun callbacks."),void 0!==window.tracardi.default)if(window.tracardi.default.getState().plugins.tracardi.initialized)for(window.tracker=window.tracardi.default;0<r.length;){var e=r.shift(),t=e.shift();tracker[t]&&tracker[t].apply(tracker,e)}else console.error("[Tracardi] Callbacks stopped. Tracker not initialized.");else console.error("[Tracardi] Callbacks stopped. Tracker not initialized. Is script url correct?")}documentReady(function(){var e,t=document.createElement("script");t.type="text/javascript",t.async=!0,void 0!==options.tracker||void 0!==options.tracker.url||void 0!==options.tracker.url.script?(null!==options.tracker.url.script?options.tracker.url.script.startsWith("http")||options.tracker.url.script.startsWith("//")?t.src=options.tracker.url.script+"/"+n:t.src=options.tracker.url.script:t.src=n,console.debug("[Tracker] Loading: "+t.src),t.addEventListener?t.addEventListener("load",function(e){i()},!1):t.onreadystatechange=function(){"complete"!==this.readyState&&"loaded"!==this.readyState||i(window.event)},(e=document.getElementsByTagName("script")[0]).parentNode.insertBefore(t,e)):console.error("[Tracker] Undefined options.tracker.url.script. This url defines location of tracker code.")})}()},{}]},{},[1])(1)});
// Init library once.
$('body').once('tracardi').each(function () {
Drupal.behaviors.tracardi.init(context);
});
}
},
init: function (context) {
if (drupalSettings.tracardi.page_view) {
Drupal.behaviors.tracardi.sendEvent('page-view', drupalSettings.tracardi.segments.page_view_payload, false);
}
if (drupalSettings.tracardi.form_submit) {
$('form').on('submit', function (e) {
// Find elements with Tracardi data attribute.
var $elements = $(this).find('[data-tracardi]');
if ($elements) {
var payload = {};
// Fill payload.
$elements.each(function () {
var $element = $(this);
payload[$element.data('tracardi')] = $element.val();
});
// Send event.
Drupal.behaviors.tracardi.sendEvent('form-submit', payload, true, true);
}
});
}
},
async sendEvent(name, payload = null, fire = true, asBeacon = false) {
if (Drupal.behaviors.tracardi_preview === undefined && window.tracker.track(name, payload, {'fire': fire, 'asBeacon': asBeacon})) {
Drupal.behaviors.tracardi.updateProfileCookies();
}
},
updateProfileCookies: function() {
const profileId = JSON.parse(window.localStorage.getItem('tracardi-profile-id'));
if (profileId === null) {
return;
}
let request = new Request(drupalSettings.tracardi.profile_cookies_endpoint.replace('profileId', profileId));
fetch(request)
.then(async (data) => {
if (!data.ok) {
throw new Error(data.status + " Profile unknown");
}
return data;
})
.then(data => data.json())
.then(data => {
for (var cookieName in data) {
// Send statistics to the dataLayer.
Drupal.behaviors.tracardi.sendStatistics(cookieName, data[cookieName]);
// Set new values in cookie.
Drupal.behaviors.tracardi.setCookie(cookieName, data[cookieName]);
// Try to send update event to Tracardi.
if (drupalSettings.tracardi.updated_cookie && !window.updatedCookie) {
Drupal.behaviors.tracardi.sendEvent('updated-cookie', {[cookieName]: data[cookieName]});
window.updatedCookie = true;
}
}
})
.catch(e => console.log('Connection error', e));
},
setCookie: function (name, value, days = 1, path = '/') {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = name + "=" + (value || "") + "; expires=" + date.toUTCString() + "; path=" + path;
},
getCookie: function (name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length).split(',').filter(x => x);
}
return [];
},
sendStatistics: function (cookieName, newValues) {
const diff = (a, b) => a.filter((v) => !b.includes(v));
window.dataLayer = window.dataLayer || [];
// Load old values from cookie and map new values to strings.
const oldValues = Drupal.behaviors.tracardi.getCookie(cookieName);
newValues = newValues.map(String)
// Calculate which ones where added and removed.
const added = diff(newValues, oldValues);
const removed = diff(oldValues, newValues);
// Send events to the dataLayer.
if (added.length) {
window.dataLayer.push({
'event': 'personalization',
'personalization': {
'cookie': cookieName,
'action': 'add',
'values': added
}
});
}
if (removed.length) {
window.dataLayer.push({
'event': 'personalization',
'personalization': {
'cookie': cookieName,
'action': 'remove',
'values': removed
}
});
}
}
};
}(jQuery, Drupal, drupalSettings));
