Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script>
- document.addEventListener('DOMContentLoaded', function() {
- // ⚙️ CONFIGURACIÓN SIMPLE
- const CONFIG = {
- WHATSAPP_NUMBER: '529512345678', // ← Tu número de WhatsApp
- // Clases CSS de los formularios que quieres que vayan a WhatsApp
- TARGET_CLASSES: [
- 'formulario-whatsapp',
- 'formulario-contacto',
- 'formulario-cotizar'
- ],
- DELAY_WHATSAPP: 2000,
- PREVENT_NORMAL_SUBMIT: true // Enviar solo por WhatsApp
- };
- // Evitar ejecución múltiple
- window.diviWhatsAppProcessed = window.diviWhatsAppProcessed || new Set();
- function inicializarFormularios() {
- let formulariosEncontrados = 0;
- CONFIG.TARGET_CLASSES.forEach(className => {
- const formularios = document.querySelectorAll(`.${className} form, form.${className}`);
- formularios.forEach((form, index) => {
- const formId = `${className}_${index}_${form.innerHTML.length}`;
- if (!window.diviWhatsAppProcessed.has(formId)) {
- formulariosEncontrados++;
- window.diviWhatsAppProcessed.add(formId);
- form.addEventListener('submit', function(e) {
- procesarFormulario(form, e);
- });
- }
- });
- });
- return formulariosEncontrados;
- }
- function procesarFormulario(form, event) {
- // Evitar envíos duplicados
- if (form.dataset.lastSubmit && (Date.now() - form.dataset.lastSubmit) < 5000) return;
- form.dataset.lastSubmit = Date.now();
- if (CONFIG.PREVENT_NORMAL_SUBMIT) {
- event.preventDefault();
- }
- // Capturar y limpiar datos
- const formData = new FormData(form);
- const datos = {};
- const camposExcluir = ['et_pb_contactform_submit_0', 'et_contact_proccess', '_wpnonce', '_wp_http_referer', 'captcha', 'g-recaptcha-response'];
- for (let [key, value] of formData.entries()) {
- const shouldExclude = camposExcluir.some(excluded =>
- key.toLowerCase().includes(excluded.toLowerCase()) ||
- key.toLowerCase().includes('nonce') ||
- key.toLowerCase().includes('referer') ||
- key.toLowerCase().includes('captcha')
- );
- if (!shouldExclude && value && value.toString().trim() !== '') {
- datos[key] = value.toString().trim();
- }
- }
- const datosOrganizados = organizarDatos(datos);
- if (CONFIG.PREVENT_NORMAL_SUBMIT) {
- abrirWhatsApp(datosOrganizados);
- } else {
- setTimeout(() => abrirWhatsApp(datosOrganizados), CONFIG.DELAY_WHATSAPP);
- }
- }
- function organizarDatos(datos) {
- const organizado = {};
- const orden = ['Nombre', 'Email', 'Teléfono', 'Asunto', 'Mensaje'];
- const camposOrdenados = {};
- const camposExtras = {};
- for (let [key, value] of Object.entries(datos)) {
- let nombreCampo;
- if (key === 'et_pb_contact_name_0' || key.includes('name')) {
- nombreCampo = 'Nombre';
- } else if (key === 'et_pb_contact_email_0' || key.includes('email')) {
- nombreCampo = 'Email';
- } else if (key === 'et_pb_contact_phone_0' || key.includes('phone')) {
- nombreCampo = 'Teléfono';
- } else if (key === 'et_pb_contact_message_0' || key.includes('message')) {
- nombreCampo = 'Mensaje';
- } else if (key === 'et_pb_contact_subject_0' || key.includes('subject')) {
- nombreCampo = 'Asunto';
- } else if (key.startsWith('et_pb_contact_')) {
- nombreCampo = key
- .replace('et_pb_contact_', '')
- .replace(/_\d+$/, '')
- .replace(/_/g, ' ')
- .replace(/\b\w/g, l => l.toUpperCase());
- } else {
- nombreCampo = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
- }
- if (nombreCampo && value) {
- if (orden.includes(nombreCampo)) {
- camposOrdenados[nombreCampo] = value;
- } else {
- camposExtras[nombreCampo] = value;
- }
- }
- }
- // Combinar en orden
- orden.forEach(campo => {
- if (camposOrdenados[campo]) organizado[campo] = camposOrdenados[campo];
- });
- Object.assign(organizado, camposExtras);
- return organizado;
- }
- function abrirWhatsApp(datos) {
- if (Object.keys(datos).length === 0) return;
- if (!CONFIG.WHATSAPP_NUMBER || CONFIG.WHATSAPP_NUMBER === '521234567890') {
- console.error('❌ Configura tu número de WhatsApp');
- return;
- }
- let mensaje = '¡Hola! Te escribo desde tu sitio web.\n\n*INFORMACION DE CONTACTO:*\n';
- for (let [campo, valor] of Object.entries(datos)) {
- mensaje += `*${campo}:* ${valor}\n`;
- }
- mensaje += '\n¡Espero tu respuesta pronto!';
- const urlWhatsApp = `https://wa.me/${CONFIG.WHATSAPP_NUMBER}?text=${encodeURIComponent(mensaje)}`;
- window.open(urlWhatsApp, '_blank');
- }
- // Inicializar una sola vez
- let yaInicializado = false;
- function iniciar() {
- if (!yaInicializado) {
- yaInicializado = true;
- inicializarFormularios();
- setTimeout(inicializarFormularios, 2000);
- }
- }
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', iniciar);
- } else {
- iniciar();
- }
- });
- </script>
Advertisement
Add Comment
Please, Sign In to add comment