oscarviedma

Código JavaScript Funcionalidad Envío por WhatsApp

Sep 3rd, 2025
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 6.01 KB | None | 0 0
  1. <script>
  2. document.addEventListener('DOMContentLoaded', function() {
  3.    
  4.     // ⚙️ CONFIGURACIÓN SIMPLE
  5.     const CONFIG = {
  6.         WHATSAPP_NUMBER: '529512345678', // ← Tu número de WhatsApp
  7.        
  8.         // Clases CSS de los formularios que quieres que vayan a WhatsApp
  9.         TARGET_CLASSES: [
  10.             'formulario-whatsapp',
  11.             'formulario-contacto',
  12.             'formulario-cotizar'
  13.         ],
  14.        
  15.         DELAY_WHATSAPP: 2000,
  16.         PREVENT_NORMAL_SUBMIT: true // Enviar solo por WhatsApp
  17.     };
  18.  
  19.     // Evitar ejecución múltiple
  20.     window.diviWhatsAppProcessed = window.diviWhatsAppProcessed || new Set();
  21.  
  22.     function inicializarFormularios() {
  23.         let formulariosEncontrados = 0;
  24.        
  25.         CONFIG.TARGET_CLASSES.forEach(className => {
  26.             const formularios = document.querySelectorAll(`.${className} form, form.${className}`);
  27.            
  28.             formularios.forEach((form, index) => {
  29.                 const formId = `${className}_${index}_${form.innerHTML.length}`;
  30.                
  31.                 if (!window.diviWhatsAppProcessed.has(formId)) {
  32.                     formulariosEncontrados++;
  33.                     window.diviWhatsAppProcessed.add(formId);
  34.                    
  35.                     form.addEventListener('submit', function(e) {
  36.                         procesarFormulario(form, e);
  37.                     });
  38.                 }
  39.             });
  40.         });
  41.        
  42.         return formulariosEncontrados;
  43.     }
  44.  
  45.     function procesarFormulario(form, event) {
  46.         // Evitar envíos duplicados
  47.         if (form.dataset.lastSubmit && (Date.now() - form.dataset.lastSubmit) < 5000) return;
  48.         form.dataset.lastSubmit = Date.now();
  49.        
  50.         if (CONFIG.PREVENT_NORMAL_SUBMIT) {
  51.             event.preventDefault();
  52.         }
  53.        
  54.         // Capturar y limpiar datos
  55.         const formData = new FormData(form);
  56.         const datos = {};
  57.        
  58.         const camposExcluir = ['et_pb_contactform_submit_0', 'et_contact_proccess', '_wpnonce', '_wp_http_referer', 'captcha', 'g-recaptcha-response'];
  59.        
  60.         for (let [key, value] of formData.entries()) {
  61.             const shouldExclude = camposExcluir.some(excluded =>
  62.                 key.toLowerCase().includes(excluded.toLowerCase()) ||
  63.                 key.toLowerCase().includes('nonce') ||
  64.                 key.toLowerCase().includes('referer') ||
  65.                 key.toLowerCase().includes('captcha')
  66.             );
  67.            
  68.             if (!shouldExclude && value && value.toString().trim() !== '') {
  69.                datos[key] = value.toString().trim();
  70.             }
  71.         }
  72.        
  73.         const datosOrganizados = organizarDatos(datos);
  74.        
  75.         if (CONFIG.PREVENT_NORMAL_SUBMIT) {
  76.             abrirWhatsApp(datosOrganizados);
  77.         } else {
  78.             setTimeout(() => abrirWhatsApp(datosOrganizados), CONFIG.DELAY_WHATSAPP);
  79.         }
  80.     }
  81.  
  82.     function organizarDatos(datos) {
  83.         const organizado = {};
  84.         const orden = ['Nombre', 'Email', 'Teléfono', 'Asunto', 'Mensaje'];
  85.         const camposOrdenados = {};
  86.         const camposExtras = {};
  87.        
  88.         for (let [key, value] of Object.entries(datos)) {
  89.             let nombreCampo;
  90.            
  91.             if (key === 'et_pb_contact_name_0' || key.includes('name')) {
  92.                 nombreCampo = 'Nombre';
  93.             } else if (key === 'et_pb_contact_email_0' || key.includes('email')) {
  94.                 nombreCampo = 'Email';
  95.             } else if (key === 'et_pb_contact_phone_0' || key.includes('phone')) {
  96.                 nombreCampo = 'Teléfono';
  97.             } else if (key === 'et_pb_contact_message_0' || key.includes('message')) {
  98.                 nombreCampo = 'Mensaje';
  99.             } else if (key === 'et_pb_contact_subject_0' || key.includes('subject')) {
  100.                 nombreCampo = 'Asunto';
  101.             } else if (key.startsWith('et_pb_contact_')) {
  102.                 nombreCampo = key
  103.                     .replace('et_pb_contact_', '')
  104.                     .replace(/_\d+$/, '')
  105.                     .replace(/_/g, ' ')
  106.                     .replace(/\b\w/g, l => l.toUpperCase());
  107.             } else {
  108.                 nombreCampo = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
  109.             }
  110.            
  111.             if (nombreCampo && value) {
  112.                if (orden.includes(nombreCampo)) {
  113.                    camposOrdenados[nombreCampo] = value;
  114.                 } else {
  115.                     camposExtras[nombreCampo] = value;
  116.                 }
  117.             }
  118.         }
  119.        
  120.         // Combinar en orden
  121.         orden.forEach(campo => {
  122.             if (camposOrdenados[campo]) organizado[campo] = camposOrdenados[campo];
  123.         });
  124.         Object.assign(organizado, camposExtras);
  125.        
  126.         return organizado;
  127.     }
  128.  
  129.     function abrirWhatsApp(datos) {
  130.         if (Object.keys(datos).length === 0) return;
  131.         if (!CONFIG.WHATSAPP_NUMBER || CONFIG.WHATSAPP_NUMBER === '521234567890') {
  132.             console.error('❌ Configura tu número de WhatsApp');
  133.             return;
  134.         }
  135.        
  136.         let mensaje = '¡Hola! Te escribo desde tu sitio web.\n\n*INFORMACION DE CONTACTO:*\n';
  137.        
  138.         for (let [campo, valor] of Object.entries(datos)) {
  139.             mensaje += `*${campo}:* ${valor}\n`;
  140.         }
  141.        
  142.         mensaje += '\n¡Espero tu respuesta pronto!';
  143.        
  144.         const urlWhatsApp = `https://wa.me/${CONFIG.WHATSAPP_NUMBER}?text=${encodeURIComponent(mensaje)}`;
  145.         window.open(urlWhatsApp, '_blank');
  146.     }
  147.  
  148.     // Inicializar una sola vez
  149.     let yaInicializado = false;
  150.    
  151.     function iniciar() {
  152.         if (!yaInicializado) {
  153.             yaInicializado = true;
  154.             inicializarFormularios();
  155.             setTimeout(inicializarFormularios, 2000);
  156.         }
  157.     }
  158.    
  159.     if (document.readyState === 'loading') {
  160.         document.addEventListener('DOMContentLoaded', iniciar);
  161.     } else {
  162.         iniciar();
  163.     }
  164. });
  165. </script>
Advertisement
Add Comment
Please, Sign In to add comment