// Конфиг по умолчанию const defaultConfig = { apiUrl: '', title: 'FAQ-Бот', position: 'bottom-right', theme: 'green' }; // Создаём виджет function initChatWidget(config) { // Стили (добавляются автоматически) const css = ` .faq-chat-widget { position: fixed; ${config.position === 'bottom-right' ? 'right: 20px;' : 'left: 20px;'} bottom: 20px; width: 300px; border-radius: 10px; background: white; box-shadow: 0 0 15px rgba(0,0,0,0.1); font-family: Arial, sans-serif; z-index: 9999; overflow: hidden; } .faq-chat-header { background: ${config.theme === 'green' ? '#4CAF50' : config.theme === 'blue' ? '#2196F3' : '#9C27B0'}; color: white; padding: 12px; text-align: center; cursor: pointer; } .faq-chat-messages { height: 250px; overflow-y: auto; padding: 10px; } .faq-chat-input { width: 100%; padding: 12px; border: none; border-top: 1px solid #eee; outline: none; } .faq-message { margin: 8px 0; padding: 8px 12px; border-radius: 5px; max-width: 80%; } .faq-user-message { background: #e3f2fd; margin-left: auto; } .faq-bot-message { background: #f5f5f5; } `; // Добавляем стили в head const styleTag = document.createElement('style'); styleTag.textContent = css; document.head.appendChild(styleTag); // HTML-структура виджета const widgetHTML = `
${config.title}
`; // Вставляем виджет в body document.body.insertAdjacentHTML('beforeend', widgetHTML); // Логика чата const widget = document.querySelector('.faq-chat-widget:last-child'); const chatInput = widget.querySelector('.faq-chat-input'); const chatMessages = widget.querySelector('.faq-chat-messages'); // Отправка сообщения в n8n async function sendMessage(message) { const response = await fetch(config.apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message }) }); return await response.json(); } // Обработчик ввода chatInput.addEventListener('keypress', async (e) => { if (e.key === 'Enter' && chatInput.value.trim()) { const userMessage = chatInput.value; chatMessages.insertAdjacentHTML('beforeend', `
${userMessage}
`); chatInput.value = ''; const botResponse = await sendMessage(userMessage); chatMessages.insertAdjacentHTML('beforeend', `
${botResponse.reply}
`); chatMessages.scrollTop = chatMessages.scrollHeight; } }); } // Загружаем конфиг из data-атрибутов const scriptTag = document.currentScript; const config = { apiUrl: scriptTag.getAttribute('data-api-url') || defaultConfig.apiUrl, title: scriptTag.getAttribute('data-title') || defaultConfig.title, position: scriptTag.getAttribute('data-position') || defaultConfig.position, theme: scriptTag.getAttribute('data-theme') || defaultConfig.theme }; // Инициализируем виджет if (config.apiUrl) { initChatWidget(config); } else { console.error('FAQ Chat Widget: Не указан data-api-url'); }