Skip to content

Instantly share code, notes, and snippets.

@Davi0k
Last active July 23, 2020 16:13
Show Gist options
  • Select an option

  • Save Davi0k/ee4e492e5ac4fb1cedea4005a600fbfe to your computer and use it in GitHub Desktop.

Select an option

Save Davi0k/ee4e492e5ac4fb1cedea4005a600fbfe to your computer and use it in GitHub Desktop.
The Official Script for the Front-End integration of Pulsing.io.
const DOMAIN = "https://api.pulsing.io", API = `${DOMAIN}/api`; //https://api.pulsing.io or http://localhost:8000
const DEFAULT = "pulse-identifier", CONSENT = "pulse-consent";
const METADATA = "pulse-data-";
const DELAY = 5000, BUBBLE = 8000, MODAL = 2000;
/*
Normal Usage: <script type="text/javascript" src="pulsing.js" id="pulse"></script>
Cookie Usage: <script id="pulse" type="text/javascript" src="pulsing.js" data-cookie="true" id="pulse"></script>
Debug Usage: <script id="pulse" type="text/javascript" src="pulsing.js" data-debug="true" id="pulse"></script>
Test Usage: <script id="pulse" type="text/javascript" src="pulsing.js" data-test="true" id="pulse"></script>
Change Identifier Label: <script id="pulse" type="text/javascript" src="pulsing.js" data-identifier="identifier" id="pulse"></script>
*/
var response = null, preferences = null;
var script = null;
var COOKIE = null, DEBUG = null, TEST = null, IDENTIFIER = null;
var X = null, Y = null;
if (document.readyState == "complete") load(null);
else document.addEventListener("DOMContentLoaded", load);
function start() {
if(preferences.bubble) bubble();
if(preferences.newsletter) newsletter(preferences.information);
track();
window.addEventListener("locationchange", seconds);
const push = history.pushState;
history.pushState = function () {
push.apply(history, arguments);
if(preferences.bubble) bubble();
seconds(); track();
response = null;
};
window.setInterval(seconds, DELAY);
}
function consent(event) {
window.localStorage.setItem(CONSENT, true);
document.getElementById("consent").remove();
start();
}
function load(event = null) {
script = window.document.getElementById("pulse");
COOKIE = script ? script.getAttribute("data-cookie") == "true" : false;
DEBUG = script ? script.getAttribute("data-debug") == "true" : false;
TEST = script ? script.getAttribute("data-test") == "true" : false;
IDENTIFIER = script
? script.getAttribute("data-identifier")
? script.getAttribute("data-identifier")
: DEFAULT
: DEFAULT;
const domain = window.location.hostname;
const request = new XMLHttpRequest();
request.open("GET", `${API}/websites/${domain}/preferences`, true);
request.onreadystatechange = function () {
if (request.readyState == 4) {
document
.getElementsByTagName("head")[0]
.insertAdjacentHTML(
"beforeend",
'<link rel="stylesheet" href="https://pulsing.io/css/modal.css"/>'
);
preferences = JSON.parse(this.responseText);
const consent = window.localStorage.getItem(CONSENT);
if (preferences.policy && consent == null) {
document.getElementsByTagName("body")[0].insertAdjacentHTML(
"beforeend",
`
<div class="micromodal-slide" id="consent" aria-hidden="true" style="display: block;">
<div class="modal__container" role="dialog" aria-modal="true" aria-labelledby="modal-1-title">
<div class="modal__header">
<h2 class="modal__title" id="modal-1-title">
Impostazioni della privacy
</h2>
</div>
<div class="modal__content" id="modal-1-content">
<p>
Questa piattaforma rispetta la tua privacy e il <code>GDPR (European Union General Data Protection Regulation)</code>. Non utilizziamo i tuoi dati per nessuno scopo da te non espressamente autorizzato.
</p>
<li>
<span class="privacyHeader">Ci autorizzi a memorizzare e analizzare i dati relativi al tuo comportamento</span> sulla nostra piattaforma per poterti fornire un\'esperienza di navigazione personalizzata?
Questa procedura implica la <span class="privacyHeader">creazione di cookie sul tuo browser</span> per assicurare la consistenza dei nostri A/B test e una corretta profilazione dell\'utente.
</li>
</div>
<a target="_blank" href="https://pulsing.io"><img src="https://pulsing.io/images/logo.png" class="modal__credits"></a>
<div class="modal__footer" >
<button class="modal__btn modal__btn-primary mrPrivacy-5" id="consentButton" onclick="consent(event)">
Concedi il consenso
</button>
<a target="_blank" href="https://pulsing.io/termini">
<button class="modal__btn modal__btn-secondary">
Termini e condizioni
</button>
</a>
</div>
</div>
</div>
`
);
}
if (preferences.policy == false || consent)
window.setTimeout(start(), MODAL);
}
};
request.send();
}
function cookie(window, name) {
const value = `; ${window.document.cookie}`, parts = value.split(`; ${name}=`);
if (parts.length == 2) return parts.pop().split(";").shift();
}
function bubble() {
const domain = window.location.hostname, url = window.location.pathname + window.location.search;
const request = new XMLHttpRequest();
request.open("GET", `${API}/websites/${domain}/bubble?url=${url}`, true);
request.onreadystatechange = function () {
if (request.readyState == 4) {
const response = JSON.parse(this.responseText);
document.getElementsByTagName("body")[0].insertAdjacentHTML(
"beforeend",
`
<div class="notificationByp fade-in" id="notifications-pulse" onclick="document.getElementById('notifications-pulse').remove()">
<div class="pulse-notification pulse-notification-font-lg pulse-notification-position-none pulse-notification-v2-classic pulse-hover-animation-float">
<div class="pulse-notification-container" style="display:inline;cursor:pointer" id="pulse-notification-v2_classic">
<div style="display:inline" class="pulse-notification-image-wrapper"><div class="pulse-notification-image-wrapper-inside">
<img class="pulse-notification-image" src="https://pulsing.io/images/pageviews.png">
</div>
</div>
<div style="display:inline" class="pulse-notification-content-wrapper">
<p class="pulse-notification-content"><strong class="pulse-strong">${response.views > 2 ? response.views : "Alcuni"} utenti</strong> hanno visitato questa pagina oggi</p>
<p class="mb0 pulse"><small>Verificato da <a href="https://pulsing.io/verifica"><span class="font-weight-400 pulsing">Pulsing.io</span></a></small></p>
</div>
<span id="pulse-close"></span>
</div>
</div>
`
);
setTimeout(function () {
const notification = document.getElementById("notifications-pulse");
if(notification) notification.remove();
}, BUBBLE);
}
};
request.send();
}
function newsletter(information) {
const identifier = window.localStorage.getItem(IDENTIFIER);
if(information == null || information.length == 0)
information = "Ti promettiamo che rispetteremo la tua privacy e useremo questo indirizzo soltanto per comunicarti notizie importanti";
if(identifier == null) {
document.getElementsByTagName("body")[0].insertAdjacentHTML(
"beforeend",
`
<div class="micromodal-slide" id="newsletter" aria-hidden="true" style="display: block;">
<div class="modal__container" role="dialog" aria-modal="true" aria-labelledby="modal-1-title">
<div class="modal__header">
<h2 class="modal__title" id="modal-1-title">Iscriviti alla Newsletter</h2>
</div>
<div class="modal__content" id="modal-1-content">
<p>${information}</p><b class="modal__b">Inserisci il tuo indirizzo email</b>
<input type="text" class="modal__form" id="modal__email" name="email"/>
</div>
<a target="_blank" href="https://pulsing.io"><img src="https://pulsing.io/images/logo.png" class="modal__credits"></a>
<div class="modal__footer">
<p class="modal__error" id="modal__error" style="display:none;">Questo indirizzo email non è valido</p>
<button class="modal__btn modal__btn-primary mrPrivacy-5" onclick="email(event)">
Iscriviti gratuitamente
</button>
<a>
<button class="modal__btn modal__btn-secondary" onclick="document.getElementById('newsletter').remove()">Non adesso</button>
</a>
</div>
</div>
</div>
`
);
}
}
function track() {
const data = {
domain: window.location.hostname,
url: window.location.pathname + window.location.search,
metadata: new Object(),
};
const identifier = COOKIE
? cookie(window, IDENTIFIER)
: window.localStorage.getItem(IDENTIFIER);
if (identifier) data.identifier = identifier;
if (TEST) data.test = TEST;
for (const label in window.localStorage)
if (label.includes(METADATA) == true) {
const key = label.replace(METADATA, new String());
const value = window.localStorage.getItem(label);
data.metadata[key] = value;
}
const json = JSON.stringify(data);
const request = new XMLHttpRequest();
request.open("POST", `${API}/logs`, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState == 4) {
switch (request.status) {
case 400:
console.warn("This browser is not supported, some essentials data cannot be retrieved.");
break;
case 404:
console.warn("No active Pulsing.io Service found for this web-site.");
break;
case 500:
console.warn("The Pulsing.io Service's server is under maintenence, your actions will not be logged until it return Online.");
break;
}
const elements = document.body.getElementsByTagName("*");
for (const element of elements)
if (
element.localName == "a" ||
element.localName == "button" ||
element.style.cursor == "pointer"
)
element.addEventListener("click", function (event) {
const interaction = {
...data,
content: element.innerText,
X: X,
Y: Y,
width: screen.width,
element: element.nodeName,
};
if (element.id) interaction.label = element.id;
const json = JSON.stringify(interaction);
const request = new XMLHttpRequest();
request.open("POST", `${API}/interactions`, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(json);
});
response = JSON.parse(this.responseText);
if (DEBUG) console.log(response, this.status);
}
};
request.send(json);
}
function seconds() {
if (response) {
const request = new XMLHttpRequest();
request.open("HEAD", `${API}/logs/${response.id}`, true);
request.send();
}
}
function email() {
const email = document.getElementById("modal__email").value;
window.localStorage.setItem(IDENTIFIER, email);
document.getElementById("newsletter").remove();
}
window.addEventListener("mousemove", function (event) {
X = event.clientX;
Y = event.clientY;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment