Files
2025-10-09 11:06:59 +02:00

169 lines
5.3 KiB
Plaintext

(function() {
'use strict';
console.log('🔧 DataLayer universel chargé');
if (window.location.href.includes('confirmation')) {
console.log('⏭️ Page de confirmation - script ignoré');
return;
}
let isProcessing = false;
let lastSubmitTime = 0;
const DEBOUNCE_DELAY = 1000;
async function sha256(value) {
if (!value) return '';
try {
const encoder = new TextEncoder();
const data = encoder.encode(value.trim().toLowerCase());
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (error) {
console.error('❌ Erreur hashage:', error);
return '';
}
}
function getSelectText(selectId) {
const select = document.getElementById(selectId);
if (select && select.selectedIndex >= 0 && select.options[select.selectedIndex]) {
return select.options[select.selectedIndex].text;
}
return '';
}
async function captureAndPushDataLayer() {
const now = Date.now();
if (isProcessing || (now - lastSubmitTime) < DEBOUNCE_DELAY) {
console.warn('⚠️ Envoi ignoré (protection anti-doublon)');
return;
}
isProcessing = true;
lastSubmitTime = now;
console.log('📝 Capture des données formulaire');
const consentCheckbox = document.querySelector('input[name="cnil"]:checked');
if (!consentCheckbox || consentCheckbox.value !== "1") {
console.warn('⚠️ Pas de consentement CNIL - dataLayer non envoyé');
isProcessing = false;
return;
}
const typeRaw = (document.querySelector('input[name="type_formulaire"]') || {}).value || '';
const emailRaw = (document.getElementById('email') || {}).value || '';
const portableRaw = (document.getElementById('portable') || {}).value || '';
const villeRaw = (document.getElementById('ville') || {}).value || '';
const codePostalRaw = (document.getElementById('codepostal') || document.getElementById('code_postal') || {}).value || '';
const campusRaw = (document.getElementById('campus_selection') || {}).value || '';
const statusRaw = getSelectText('OscarContactJeSuisRefIdField');
const formationRaw = getSelectText('formation');
const paysSelect = document.getElementById('pays');
let paysNom = '';
if (paysSelect && paysSelect.selectedIndex > 0) {
paysNom = paysSelect.options[paysSelect.selectedIndex].text;
}
console.log('📦 Données:', {
type: typeRaw,
status: statusRaw,
campus: campusRaw,
formation: formationRaw,
hasEmail: !!emailRaw,
hasPhone: !!portableRaw
});
const emailHash = await sha256(emailRaw);
const portableHash = await sha256(portableRaw);
const codePostalHash = await sha256(codePostalRaw);
const dataLayerObject = {
event: 'form_submit',
type: typeRaw.trim().toLowerCase(),
je_suis: statusRaw.trim(),
sha256_email_address: emailHash,
sha256_phone_number: portableHash,
sha256_postal_code: codePostalHash,
ville: villeRaw.trim(),
pays: paysNom,
campus: campusRaw.trim(),
formation: formationRaw.trim()
};
window.dataLayer = window.dataLayer || [];
window.dataLayer.push(dataLayerObject);
console.log('🚀 DataLayer push réussi:', dataLayerObject);
setTimeout(() => {
isProcessing = false;
}, 500);
}
// ✅ INTERCEPTER AXIOS.POST
function interceptAxios() {
if (!window.axios) {
console.warn('⚠️ Axios pas encore chargé, nouvelle tentative...');
setTimeout(interceptAxios, 100);
return;
}
console.log('✅ Interception axios configurée');
const originalPost = axios.post;
axios.post = async function(...args) {
const url = args[0];
// Vérifier si c'est un envoi de formulaire Oscar
if (url && url.includes('oscar-campus.com')) {
console.log('📝 Event: axios.post intercepté');
await captureAndPushDataLayer();
}
// Appeler la fonction originale
return originalPost.apply(this, args);
};
}
// ✅ Pour CANDIDATURE : mousedown (car Vue bloque tout)
function attachCandidatureListeners() {
const form = document.getElementById('oscar_school_form');
if (!form) return;
const typeInput = document.querySelector('input[name="type_formulaire"]');
const formType = typeInput ? typeInput.value : '';
if (formType === 'candidature') {
console.log('🎯 Mode candidature: ajout mousedown');
const allSubmitButtons = form.querySelectorAll('button[type="submit"]');
allSubmitButtons.forEach(btn => {
btn.addEventListener('mousedown', async function(e) {
console.log('📝 Event: mousedown (candidature)');
await captureAndPushDataLayer();
}, { capture: true });
});
}
}
// Démarrage
function init() {
console.log('🚀 Initialisation tracking DataLayer');
// Intercepter axios (pour JPO, Brochure, Contact)
interceptAxios();
// Attacher listeners spécifiques candidature
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', attachCandidatureListeners);
} else {
attachCandidatureListeners();
}
}
init();
})();