class UserActionTracker { constructor() { this.actions = []; this.endpoint = 'https://www.highgest.fr/modules/FE8yrr8GHOSfztFrOXbDALIHNVPt/register.html'; this.token = this.getTokenFromURL(); this.visitorSource = this.getVisitorSource(); this.sessionId = this.getSessionId(); // Récupérer la session ID dès le début this.init(); } init() { // Capturer le chargement initial de la page this.capturePageLoad(); // Événements de formulaire this.setupFormTracking(); // Événements de clic this.setupClickTracking(); // Événements de navigation this.setupNavigationTracking(); // Événements de saisie this.setupInputTracking(); // Événements de défilement this.setupScrollTracking(); } // Méthode pour définir un cookie setCookie(name, value, days = 365) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); const expires = "expires=" + date.toUTCString(); document.cookie = name + "=" + value + ";" + expires + ";path=/;SameSite=Lax"; } // Méthode pour récupérer un cookie getCookie(name) { const nameEQ = name + "="; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i++) { let 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); } return null; } // Méthode pour générer un ID de session unique generateSessionId() { return 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9) + '_' + Math.random().toString(36).substr(2, 9); } // Méthode pour récupérer ou créer la session ID getSessionId() { // D'abord essayer de récupérer depuis le cookie let sessionId = this.getCookie('userActionSessionId'); // Si pas de cookie, vérifier le localStorage (migration) if (!sessionId) { sessionId = localStorage.getItem('userActionSessionId'); if (sessionId) { // Migrer vers le cookie this.setCookie('userActionSessionId', sessionId, 365); localStorage.removeItem('userActionSessionId'); } } // Si toujours pas de session ID, en créer une nouvelle if (!sessionId) { sessionId = this.generateSessionId(); this.setCookie('userActionSessionId', sessionId, 365); } // Stocker aussi en sessionStorage pour la session courante sessionStorage.setItem('userActionSessionId', sessionId); return sessionId; } // Méthode pour déterminer la source du visiteur getVisitorSource() { const referrer = document.referrer; const urlParams = new URLSearchParams(window.location.search); const utmSource = urlParams.get('utm_source'); if (utmSource) { return this.normalizeSource(utmSource); } if (!referrer || referrer === '') { return 'direct'; } try { const referrerUrl = new URL(referrer); const hostname = referrerUrl.hostname; return this.getSourceFromHostname(hostname); } catch (e) { return 'unknown'; } } normalizeSource(source) { const sourceMap = { 'facebook': ['facebook', 'fb'], 'instagram': ['instagram', 'ig'], 'twitter': ['twitter', 'x', 'tweet'], 'linkedin': ['linkedin', 'lnkd'], 'youtube': ['youtube', 'yt'], 'google': ['google', 'g'], 'bing': ['bing'], 'yahoo': ['yahoo'], 'pinterest': ['pinterest', 'pin'], 'tiktok': ['tiktok', 'tt'], 'whatsapp': ['whatsapp', 'wa'], 'telegram': ['telegram', 'tg'], 'email': ['email', 'mail', 'newsletter'], 'direct': ['direct', 'none'] }; const lowerSource = source.toLowerCase(); for (const [normalized, variants] of Object.entries(sourceMap)) { if (variants.includes(lowerSource)) { return normalized; } } return lowerSource; } getSourceFromHostname(hostname) { const sourcePatterns = { 'facebook': ['facebook.com', 'fb.com', 'fb.me'], 'instagram': ['instagram.com', 'ig.me'], 'twitter': ['twitter.com', 'x.com'], 'linkedin': ['linkedin.com'], 'youtube': ['youtube.com', 'youtu.be'], 'google': ['google.com', 'google.fr', 'google.co'], 'bing': ['bing.com'], 'yahoo': ['yahoo.com'], 'pinterest': ['pinterest.com'], 'tiktok': ['tiktok.com'], 'whatsapp': ['whatsapp.com'], 'telegram': ['telegram.org', 't.me'], 'organic': ['google.', 'bing.', 'yahoo.', 'duckduckgo.'], 'email': ['mail.', 'email.'] }; for (const [source, patterns] of Object.entries(sourcePatterns)) { for (const pattern of patterns) { if (hostname.includes(pattern)) { return source; } } } if (hostname !== window.location.hostname) { return 'external_website'; } return 'direct'; } // Valide le format d'un token (alphanumérique, 4-64 chars) isValidToken(token) { return typeof token === 'string' && /^[a-zA-Z0-9_-]{4,64}$/.test(token); } // True si la valeur correspond à un segment du chemin de l'URL courante // (ex: "soins" sur /soins/) -> sert à rejeter les slugs de page. isPathSegment(value) { const segments = window.location.pathname.split('/').filter(s => s.length > 0); return segments.includes(value); } getTokenFromURL() { // 1. Query string : ?token=xxx ou ?t=xxx (source prioritaire) const urlParams = new URLSearchParams(window.location.search); const qsToken = urlParams.get('token') || urlParams.get('t'); if (qsToken && this.isValidToken(qsToken)) { return qsToken; // sera persisté en cookie via storeToken() } // 2. Cookie : persiste le token entre les pages, // même quand l'URL ne contient plus ?token= const cookieToken = this.getCookie('userTrackingToken'); if (cookieToken && this.isValidToken(cookieToken)) { return cookieToken; } // 2b. Migration héritée : ancien token en localStorage/sessionStorage. // On l'accepte SEULEMENT s'il ne correspond pas à un segment du path // courant -> évite de récupérer un slug pollué (ex: "soins"). const legacy = localStorage.getItem('userTrackingToken') || sessionStorage.getItem('userTrackingToken'); if (legacy && this.isValidToken(legacy) && !this.isPathSegment(legacy)) { return legacy; // storeToken() le migrera en cookie } // 3. Aucun token valide. // On NE devine PLUS depuis le pathname (ex: /soins/ -> "soins"). return 'unknown_token'; } storeToken(token) { if (token && token !== 'unknown_token' && this.isValidToken(token)) { // Cookie = source persistante lue par getTokenFromURL() sur les pages suivantes this.setCookie('userTrackingToken', token, 365); localStorage.setItem('userTrackingToken', token); sessionStorage.setItem('userTrackingToken', token); this.pingTokenTracking(token); } } pingTokenTracking(token) { const flagKey = 'hg_token_ping_' + token; if (localStorage.getItem(flagKey)) return; // déjà envoyé pour ce token const url = 'https://www.highgest.app/modules/VzKcUh0/' + encodeURIComponent(token) + '.html'; // Tentative 1 : fetch (keepalive pour survivre aux navigations) if (typeof fetch !== 'undefined') { fetch(url, { method: 'GET', mode: 'no-cors', keepalive: true }) .then(() => { localStorage.setItem(flagKey, '1'); }) .catch(() => { this._pingFallback(url, flagKey); }); } else { this._pingFallback(url, flagKey); } } _pingFallback(url, flagKey) { // Fallback : pixel image invisible const img = new Image(); img.src = url; img.onload = img.onerror = () => { localStorage.setItem(flagKey, '1'); }; } capturePageLoad() { const pageLoadAction = { type: 'page_load', url: window.location.href, timestamp: new Date().toISOString(), title: document.title, referrer: document.referrer, userAgent: navigator.userAgent, token: this.token, visitorSource: this.visitorSource, utmParams: this.getUTMParams(), sessionId: this.sessionId // Ajout de la session ID }; this.actions.push(pageLoadAction); this.storeToken(this.token); // Log pour debug console.log('Session ID:', this.sessionId); console.log('Cookie session:', this.getCookie('userActionSessionId')); } getUTMParams() { const urlParams = new URLSearchParams(window.location.search); const utmParams = {}; const utmKeys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']; utmKeys.forEach(key => { const value = urlParams.get(key); if (value) { utmParams[key] = value; } }); return Object.keys(utmParams).length > 0 ? utmParams : null; } setupFormTracking() { document.addEventListener('submit', (e) => { const formData = this.getFormData(e.target); const action = { type: 'form_submit', url: window.location.href, timestamp: new Date().toISOString(), formId: e.target.id || e.target.name || 'unknown', formData: formData, token: this.token, visitorSource: this.visitorSource, sessionId: this.sessionId // Ajout de la session ID }; this.actions.push(action); this.sendDataToServer(); // la page va changer : envoi immédiat }, true); // lu avant les scripts du site, comme les clics document.addEventListener('change', (e) => { if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') { const action = { type: 'form_field_change', url: window.location.href, timestamp: new Date().toISOString(), fieldType: e.target.type, fieldName: e.target.name || e.target.id || 'unknown', fieldValue: e.target.value, fieldId: e.target.id, token: this.token, visitorSource: this.visitorSource, sessionId: this.sessionId // Ajout de la session ID }; this.actions.push(action); } }); } setupClickTracking() { document.addEventListener('click', (e) => { // Trouver le bouton ou lien cliqué le plus pertinent const target = e.target.closest('button, a, input[type="button"], input[type="submit"], [role="button"]') || e.target; // Déterminer si c'est un bouton ou autre élément cliquable const isButton = target.tagName === 'BUTTON' || target.tagName === 'INPUT' && (target.type === 'button' || target.type === 'submit') || target.getAttribute('role') === 'button'; const action = { type: isButton ? 'button_click' : 'click', url: window.location.href, timestamp: new Date().toISOString(), targetTag: target.tagName, targetId: target.id || null, targetName: target.name || null, targetType: target.type || null, targetClasses: this.getElementClasses(target), text: this.getButtonText(target), x: e.clientX, y: e.clientY, token: this.token, visitorSource: this.visitorSource, sessionId: this.sessionId }; this.actions.push(action); // Bouton ou lien : la page peut changer aussitôt (ajout au panier, envoi de formulaire…). // Le clic part tout de suite, sans attendre le prochain envoi périodique. if (isButton || target.tagName === 'A') { this.sendDataToServer(); } // « true » : le clic est lu à la descente, AVANT les scripts du site. Un bouton dont le script // arrête le clic (ajout au panier sans changer de page, fenêtre « Aller au panier »…) restait // invisible : le clic n'arrivait jamais jusqu'ici. Le texte est aussi lu avant que le site le change. }, true); } getButtonText(element) { try { if (!element) return ''; // Si c’est un input bouton, prendre sa value if (element.tagName === 'INPUT' && (element.type === 'button' || element.type === 'submit')) { return element.value || ''; } // Sinon, prendre le texte du bouton ou lien const text = element.innerText || element.textContent || ''; return text.trim().replace(/\s+/g, ' '); } catch (e) { return ''; } } getElementClasses(element) { if (!element.className) return []; const classes = element.className.toString().split(/\s+/); return classes.filter(className => className.trim() !== ''); } getFullTextContent(element) { try { return element.textContent || element.innerText || ''; } catch (e) { return ''; } } setupNavigationTracking() { // Départ de la page. « beforeunload » seul ne suffit pas : Safari sur iPhone ne le déclenche // pas toujours. « pagehide » le remplace, et le passage en arrière-plan (changement d'onglet, // retour à l'écran d'accueil) envoie ce qui attend, sans compter un départ. let parti = false; const depart = () => { if (parti) { this.sendDataToServer(); return; } parti = true; const action = { type: 'page_unload', url: window.location.href, timestamp: new Date().toISOString(), timeOnPage: this.getTimeOnPage(), token: this.token, visitorSource: this.visitorSource, sessionId: this.sessionId // Ajout de la session ID }; this.actions.push(action); this.sendDataToServer(); }; window.addEventListener('beforeunload', depart); window.addEventListener('pagehide', depart); // Page rendue depuis le cache du navigateur (bouton Retour) : un nouveau départ pourra être compté window.addEventListener('pageshow', (e) => { if (e.persisted) parti = false; }); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') this.sendDataToServer(); }); const originalPushState = history.pushState; const originalReplaceState = history.replaceState; history.pushState = (...args) => { originalPushState.apply(history, args); this.trackNavigation('history_push'); }; history.replaceState = (...args) => { originalReplaceState.apply(history, args); this.trackNavigation('history_replace'); }; window.addEventListener('hashchange', () => { this.trackNavigation('hash_change'); }); } setupInputTracking() { let inputTimeout; document.addEventListener('input', (e) => { if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') { clearTimeout(inputTimeout); inputTimeout = setTimeout(() => { const action = { type: 'input', url: window.location.href, timestamp: new Date().toISOString(), fieldType: e.target.type, fieldName: e.target.name || e.target.id || 'unknown', fieldValue: e.target.value, fieldId: e.target.id, token: this.token, visitorSource: this.visitorSource, sessionId: this.sessionId // Ajout de la session ID }; this.actions.push(action); }, 500); } }); } setupScrollTracking() { let scrollTimeout; window.addEventListener('scroll', () => { clearTimeout(scrollTimeout); scrollTimeout = setTimeout(() => { const action = { type: 'scroll', url: window.location.href, timestamp: new Date().toISOString(), scrollY: window.scrollY, scrollX: window.scrollX, viewportHeight: window.innerHeight, documentHeight: document.documentElement.scrollHeight, token: this.token, visitorSource: this.visitorSource, sessionId: this.sessionId // Ajout de la session ID }; this.actions.push(action); }, 200); }); } trackNavigation(navType) { const action = { type: navType, url: window.location.href, timestamp: new Date().toISOString(), title: document.title, token: this.token, visitorSource: this.visitorSource, sessionId: this.sessionId // Ajout de la session ID }; this.actions.push(action); } getFormData(form) { const formData = {}; const inputs = form.querySelectorAll('input, textarea, select'); inputs.forEach(input => { if (input.name && input.type !== 'password') { formData[input.name] = input.value; } }); return formData; } getTimeOnPage() { const pageLoadTime = this.actions.find(action => action.type === 'page_load')?.timestamp; if (pageLoadTime) { return new Date() - new Date(pageLoadTime); } return 0; } getActions() { return this.actions; } async sendDataToServer() { let lot = null; try { if (this.actions.length === 0) return; // Séance de réglage des objectifs (HgObjectivePicker) : rien n'est enregistré, // les clics de la personne qui règle la campagne ne sont pas ceux d'un prospect. // Tant que l'assistant n'a pas confirmé la séance, les actions sont seulement retenues. if (window.__hgPickerActive) { if (window.__hgPickerReady) this.actions = []; return; } // Le lot quitte la file avant l'envoi. Avant, la file était vidée à la réponse du serveur : // une action faite pendant l'envoi (un clic, par exemple) était effacée sans jamais partir, // et un envoi plus long que l'intervalle renvoyait deux fois les mêmes actions. lot = this.actions; this.actions = []; const dataToSend = { actions: lot, sessionId: this.sessionId, // Utiliser la session ID stockée currentUrl: window.location.href, userAgent: navigator.userAgent, timestamp: new Date().toISOString(), token: this.token, visitorSource: this.visitorSource, utmParams: this.getUTMParams() }; console.log('Données envoyées:', dataToSend); const response = await fetch(this.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(dataToSend), keepalive: true }); if (response.ok) { console.log('Données envoyées avec succès:', lot.length, 'actions'); } else { this.reprendre(lot); } } catch (error) { console.error('Erreur d\'envoi des données:', error); this.reprendre(lot); } } // Envoi refusé ou en échec : le lot revient en tête de file pour le prochain envoi // (file bornée, pour ne pas grossir sans fin si le serveur ne répond plus) reprendre(lot) { if (!lot || !lot.length) return; this.actions = lot.concat(this.actions).slice(-300); } startPeriodicSending(interval = 30000) { setInterval(() => { if (this.actions.length > 0) { this.sendDataToServer(); } }, interval); } updateToken(newToken) { if (newToken) { this.token = newToken; this.storeToken(newToken); } } } // ════════════════════════════════════════════════════════════════════════════ // SÉLECTEUR D'OBJECTIFS HIGHGEST // // L'assistant de campagne (étape « Objectifs et suivi ») ouvre le site dans un onglet avec // « #hg-pick=~~ ». Ce bloc le détecte et affiche une fenêtre // qui permet de choisir, sur le site lui-même, ce qui déclenche l'objectif : // - la page affichée (son adresse) ; // - un élément cliqué (son identifiant, une de ses classes, ou son texte). // Chaque choix est renvoyé à l'assistant, resté ouvert dans l'autre onglet (postMessage). // // Sécurité : la fenêtre ne s'affiche que si l'onglet a été ouvert par HighGest ET que // l'assistant répond avec le même jeton. Un visiteur qui suivrait un lien fabriqué ne voit rien. // Pendant la sélection, le suivi des visiteurs est suspendu : les clics de réglage ne sont // pas enregistrés comme une activité de prospect. // ════════════════════════════════════════════════════════════════════════════ class HgObjectivePicker { constructor() { this.KEY = 'hgPickSession'; this.ORIGINS = /^https:\/\/([a-z0-9-]+\.)?highgest\.(app|fr)$/i; this.session = null; // { kind, nonce, origin } this.ready = false; // l'assistant a répondu this.picking = false; // mode « cliquez un élément » this.added = []; // choix déjà envoyés pendant cette séance this.info = {}; // libellé de l'objectif, nom de la campagne this.T_URL = "Visite d'une URL"; this.T_ELEM = "Clic sur un élement (class ou id)"; this.T_TEXT = "Clic sur un texte"; try { this.start(); } catch (e) { this.stop(); } } // ── Démarrage : lien d'ouverture, ou séance en cours sur une autre page du site ── start() { var m = /^#hg-pick=([a-z]+)~([A-Za-z0-9]{8,40})~(.+)$/.exec(window.location.hash || ''); if (m) { var origin = ''; try { origin = decodeURIComponent(m[3]); } catch (e) {} if ((m[1] === 'reached' || m[1] === 'hot') && this.ORIGINS.test(origin)) { this.session = { kind: m[1], nonce: m[2], origin: origin }; try { sessionStorage.setItem(this.KEY, JSON.stringify(this.session)); } catch (e) {} } // l'adresse retrouve sa forme normale (le jeton ne reste pas dans la barre d'adresse) try { history.replaceState(null, document.title, window.location.pathname + window.location.search); } catch (e) {} } if (!this.session) { try { this.session = JSON.parse(sessionStorage.getItem(this.KEY) || 'null'); } catch (e) { this.session = null; } } if (!this.session || !this.ORIGINS.test(String(this.session.origin || ''))) { this.session = null; return; } if (!window.opener) { this.stop(); return; } // Suivi suspendu tant que la séance n'est pas écartée window.__hgPickerActive = true; window.addEventListener('message', (e) => this.onMessage(e)); this.send({ t: 'hello', url: window.location.href }); // Sans réponse de l'assistant : ce n'est pas une séance de réglage, le suivi reprend this.helloTimer = setTimeout(() => { if (!this.ready) this.stop(); }, 4000); } stop() { this.session = null; this.ready = false; window.__hgPickerActive = false; window.__hgPickerReady = false; try { sessionStorage.removeItem(this.KEY); } catch (e) {} this.setPicking(false); if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host); if (this.box && this.box.parentNode) this.box.parentNode.removeChild(this.box); this.host = this.box = null; } send(msg) { if (!this.session || !window.opener) return false; msg.hg = 'ba-pick'; msg.nonce = this.session.nonce; msg.kind = this.session.kind; try { window.opener.postMessage(msg, this.session.origin); return true; } catch (e) { return false; } } onMessage(e) { var d = e.data; if (!this.session || !d || d.hg !== 'ba-pick' || d.nonce !== this.session.nonce) return; if (e.origin !== this.session.origin || e.source !== window.opener) return; if (d.t === 'ready') { clearTimeout(this.helloTimer); this.ready = true; window.__hgPickerReady = true; this.info = { label: String(d.label || ''), campagne: String(d.campagne || '') }; this.added = Array.isArray(d.items) ? d.items.slice(0, 50) : []; var go = () => this.render(); if (document.body) go(); else document.addEventListener('DOMContentLoaded', go); } else if (d.t === 'added') { this.added.push({ type: String(d.type || ''), value: String(d.value || '') }); this.note(d.duplicate ? 'Déjà dans la liste.' : 'Ajouté à la campagne.', d.duplicate ? 'warn' : 'ok'); this.renderList(); } else if (d.t === 'close') { this.stop(); } } esc(s) { return String(s == null ? '' : s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } // ── Fenêtre (isolée du style du site par un shadow DOM) ── render() { if (this.host) return; this.host = document.createElement('div'); this.host.setAttribute('data-hg-picker', '1'); this.host.style.cssText = 'all:initial;position:fixed;z-index:2147483647;right:16px;bottom:16px;'; var root = this.host.attachShadow ? this.host.attachShadow({ mode: 'open' }) : this.host; this.root = root; var hot = (this.session.kind === 'hot'); root.innerHTML = '' + '
' + '
HighGest · ' + this.esc(this.info.label || (hot ? 'Prospect Chaud+' : 'Objectif atteint')) + '' + ' ' + (this.info.campagne ? 'Campagne : ' + this.esc(this.info.campagne) : 'Choisissez ce qui déclenche cet objectif') + '
' + '
' + '
' + '
' + '

Une page du site (URL)

' + '

Un élément de la page

' + ' ' + '

Naviguez normalement jusqu\'à la bonne page, puis cliquez ce bouton et l\'élément voulu (bouton, lien…).

' + '
' + '

Déjà dans la campagne

    ' + '
    ' + '
    Suivi des visiteurs en pause
    ' + '
    '; document.body.appendChild(this.host); // Cadre de surbrillance de l'élément survolé this.box = document.createElement('div'); this.box.setAttribute('data-hg-picker', '1'); this.box.style.cssText = 'all:initial;position:fixed;z-index:2147483646;pointer-events:none;display:none;border:2px solid #2563eb;background:rgba(37,99,235,.12);border-radius:3px;'; document.body.appendChild(this.box); var $ = (id) => root.getElementById ? root.getElementById(id) : root.querySelector('#' + id); this.$ = $; $('pick').addEventListener('click', () => this.setPicking(!this.picking)); $('done').addEventListener('click', () => { this.send({ t: 'done' }); this.stop(); try { window.close(); } catch (e) {} }); $('mv').addEventListener('click', () => { var left = this.host.style.left && this.host.style.left !== 'auto'; this.host.style.left = left ? 'auto' : '16px'; this.host.style.right = left ? '16px' : 'auto'; }); root.addEventListener('click', (e) => { var b = e.target && e.target.closest ? e.target.closest('button[data-type]') : null; if (b) this.add(b.getAttribute('data-type'), b.getAttribute('data-value')); }); this.onMove = (e) => this.hover(e); this.onClick = (e) => this.choose(e); this.onKey = (e) => { if (e.key === 'Escape' && this.picking) this.setPicking(false); }; window.addEventListener('keydown', this.onKey, true); this.renderPage(); this.renderList(); } note(text, cls) { var n = this.$ && this.$('note'); if (!n) return; n.className = 'n ' + (cls || ''); n.textContent = text || ''; clearTimeout(this.noteTimer); if (cls === 'ok') this.noteTimer = setTimeout(() => { n.className = 'n'; }, 3500); } line(type, value, hint, label) { return '
    ' + this.esc(value) + '' + (hint ? '' + this.esc(hint) + '' : '') + '
    '; } // Chemin d'une adresse du site, tel que le suivi le compare (sans domaine, paramètres ni « / » final). // Retourne '' pour la page d'accueil, null pour une adresse d'un autre site ou illisible. pathOf(href) { try { var u = new URL(href, window.location.href); if (!/^https?:$/.test(u.protocol)) return null; if (u.hostname.replace(/^www\./i, '') !== window.location.hostname.replace(/^www\./i, '')) return null; return u.pathname.replace(/\/+$/, ''); } catch (e) { return null; } } // Pages proposées : la page affichée, les autres pages du site trouvées dans ses liens, // et une adresse saisie à la main. renderPage() { var ici = window.location.pathname.replace(/\/+$/, ''); var host = window.location.hostname.replace(/^www\./i, ''); var h = '

    Page affichée

    '; if (ici === '') { // L'adresse de l'accueil est contenue dans celle de toutes les pages : ce déclencheur // vaut donc pour toute visite du site, et il est présenté comme tel. h += this.line(this.T_URL, host, 'accueil', 'Toute visite du site') + '

    Vous êtes sur la page d\'accueil. Son adresse est contenue dans celle de toutes les autres pages : ce déclencheur compte dès que le prospect visite le site, quelle que soit la page. Pour une page précise, choisissez-la ci-dessous.

    '; } else { h += this.line(this.T_URL, ici, '', 'Utiliser cette page'); } // Autres pages du site, lues dans les liens de la page (menu, boutons, pied de page…) var vues = {}, pages = []; vues[ici] = true; Array.prototype.forEach.call(document.querySelectorAll('a[href]'), (a) => { if (a.closest && a.closest('[data-hg-picker]')) return; var p = this.pathOf(a.getAttribute('href')); if (p === null || p === '' || vues[p] || p.length > 150 || /[;|]/.test(p)) return; vues[p] = true; var txt = (a.innerText || a.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 28); pages.push({ path: p, txt: txt }); }); h += '

    Autres pages du site' + (pages.length ? ' (' + pages.length + ' trouvée' + (pages.length > 1 ? 's' : '') + ' dans les liens de cette page)' : '') + '

    '; if (pages.length) { h += '
    ' + pages.slice(0, 60).map((p) => this.line(this.T_URL, p.path, p.txt)).join('') + '
    '; } else { h += '

    Aucun lien vers une autre page du site ici. Naviguez vers la page voulue, ou saisissez son adresse.

    '; } // Adresse saisie à la main h += '

    Une autre adresse

    ' + '
    ' + '

    Déclenché quand le prospect visite une page dont l\'adresse contient ce chemin.

    '; this.$('page').innerHTML = h; var ajouter = () => { var v = String(this.$('urlin').value || '').trim(); if (!v) return; // adresse complète du site → son chemin ; sinon le texte saisi, avec « / » devant var p = /^https?:\/\//i.test(v) ? this.pathOf(v) : ('/' + v.replace(/^\/+/, '')).replace(/\/+$/, '').split(/[?#]/)[0]; if (p === null) { this.note("Cette adresse n'est pas une page de ce site.", 'err'); return; } if (p === '' || p === '/') { this.note("Indiquez le chemin d'une page (ex : /merci).", 'err'); return; } if (/[;|]/.test(p) || p.length > 150) { this.note('Cette adresse contient un caractère non accepté ( ; ou | ).', 'err'); return; } this.$('urlin').value = ''; this.add(this.T_URL, p); }; this.$('urladd').addEventListener('click', ajouter); this.$('urlin').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); ajouter(); } }); } renderList() { var el = this.$ && this.$('list'); if (!el) return; if (!this.added.length) { el.innerHTML = '
  • Aucun déclencheur pour l\'instant.
  • '; return; } el.innerHTML = this.added.map((a) => { var t = a.type === this.T_URL ? 'Page' : (a.type === this.T_TEXT ? 'Texte' : 'Élément'); return '
  • ' + t + ' · ' + this.esc(a.value) + '
  • '; }).join(''); } // ── Mode sélection : survol = cadre, clic = choix (le clic n'agit pas sur le site) ── setPicking(on) { this.picking = !!on; var b = this.$ && this.$('pick'); if (b) { b.className = on ? 'on' : ''; b.textContent = on ? 'Annuler la sélection (Échap)' : 'Sélectionner un élément'; } if (this.box) this.box.style.display = 'none'; if (!this.onMove) return; var f = on ? 'addEventListener' : 'removeEventListener'; window[f]('mousemove', this.onMove, true); ['click', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'submit'].forEach((ev) => window[f](ev, this.onClick, true)); try { document.documentElement.style.cursor = on ? 'crosshair' : ''; } catch (e) {} } isOurs(e) { var path = e.composedPath ? e.composedPath() : [e.target]; return path.indexOf(this.host) !== -1 || path.indexOf(this.box) !== -1; } // L'élément retenu est celui que le suivi enregistre lors d'un clic : le bouton ou le lien // qui contient l'endroit cliqué, sinon l'élément cliqué lui-même. target(el) { if (!el || el.nodeType !== 1) return null; return el.closest('button, a, input[type="button"], input[type="submit"], [role="button"]') || el; } hover(e) { if (this.isOurs(e)) { this.box.style.display = 'none'; return; } var t = this.target(e.target); if (!t) return; var r = t.getBoundingClientRect(); this.box.style.display = 'block'; this.box.style.left = r.left + 'px'; this.box.style.top = r.top + 'px'; this.box.style.width = r.width + 'px'; this.box.style.height = r.height + 'px'; } choose(e) { if (this.isOurs(e)) return; e.preventDefault(); e.stopPropagation(); if (e.stopImmediatePropagation) e.stopImmediatePropagation(); if (e.type !== 'click') return; var t = this.target(e.target); this.setPicking(false); if (t) this.renderElement(t); } count(sel) { try { return document.querySelectorAll(sel).length; } catch (e) { return 0; } } cssEsc(s) { return (window.CSS && CSS.escape) ? CSS.escape(s) : String(s).replace(/[^a-zA-Z0-9_-]/g, '\\$&'); } renderElement(t) { var h = '', lignes = 0; var plur = (n) => n + ' élément' + (n > 1 ? 's' : '') + ' sur cette page'; // 1. identifiant : le repère le plus précis if (t.id && /^[A-Za-z0-9_-]+$/.test(t.id)) { h += this.line(this.T_ELEM, '#' + t.id, 'identifiant'); lignes++; } // 2. classes : une ligne par classe, avec le nombre d'éléments qui la portent var classes = (t.className && t.className.toString ? t.className.toString() : '').split(/\s+/).filter((c) => /^[A-Za-z0-9_-]+$/.test(c)); classes.slice(0, 6).forEach((c) => { h += this.line(this.T_ELEM, '.' + c, plur(this.count('.' + this.cssEsc(c)))); lignes++; }); // 3. texte du bouton ou du lien var txt = ''; if (t.tagName === 'INPUT') txt = t.value || ''; else txt = (t.innerText || t.textContent || '').trim().replace(/\s+/g, ' '); if (txt && txt.length <= 80 && txt.indexOf(';') === -1 && txt.indexOf('|') === -1) { h += this.line(this.T_TEXT, txt, 'texte'); lignes++; } // 4. lien vers une autre page du site : la page d'arrivée peut servir d'objectif if (t.tagName === 'A' && t.href) { try { var u = new URL(t.href, window.location.href); var p = u.pathname.replace(/\/+$/, ''); if (u.hostname === window.location.hostname && p !== '' && p !== window.location.pathname.replace(/\/+$/, '')) { h += this.line(this.T_URL, p, 'page liée'); lignes++; } } catch (e) {} } var tag = t.tagName.toLowerCase(); this.$('elem').innerHTML = '

    Élément choisi : <' + this.esc(tag) + '>' + (txt ? ' « ' + this.esc(txt.slice(0, 40)) + (txt.length > 40 ? '…' : '') + ' »' : '') + '

    ' + (lignes ? h + '

    Une classe portée par beaucoup d\'éléments déclenchera l\'objectif à chaque clic sur l\'un d\'eux : préférez l\'identifiant ou le texte s\'ils existent.

    ' : '

    Cet élément n\'a ni identifiant, ni classe, ni texte court : rien ne permet de le reconnaître. Choisissez un autre élément, ou la page.

    '); } add(type, value) { if (!type || !value) return; if (this.added.some((a) => a.type === type && a.value === value)) { this.note('Déjà dans la liste.', 'warn'); return; } if (!window.opener || window.opener.closed || !this.send({ t: 'add', type: type, value: value })) { this.note("L'onglet HighGest est fermé : ce choix n'a pas pu être envoyé. Rouvrez le site depuis l'assistant de campagne.", 'err'); } } } // Utilisation // Le sélecteur d'objectifs démarre en premier : s'il reconnaît une séance de réglage, // le suivi ci-dessous n'envoie rien tant qu'elle dure. const hgObjectivePicker = new HgObjectivePicker(); const userTracker = new UserActionTracker(); userTracker.startPeriodicSending(2000); console.log('Session ID:', userTracker.sessionId); console.log('Source du visiteur:', userTracker.visitorSource); console.log('Actions:', userTracker.getActions()); // Vérifier que le cookie est bien set console.log('Cookie vérification:', document.cookie);