const chaterboxsiteurl = 'chaterbox.mykt.co.uk'; var chatToggleButton = document.createElement('button'); chatToggleButton.style.position = 'fixed'; chatToggleButton.style.bottom = '20px'; chatToggleButton.style.right = '20px'; chatToggleButton.style.padding = '10px'; chatToggleButton.style.backgroundColor = '#007bff'; chatToggleButton.style.color = '#fff'; chatToggleButton.style.border = 'none'; chatToggleButton.style.borderRadius = '50%'; chatToggleButton.style.cursor = 'pointer'; chatToggleButton.innerText = 'Chat'; document.body.appendChild(chatToggleButton); // Create chat widget elements and apply styling var chatWidgetContainer = document.createElement('div'); chatWidgetContainer.style.position = 'fixed'; chatWidgetContainer.style.bottom = '20px'; chatWidgetContainer.style.right = '20px'; chatWidgetContainer.style.width = '320px'; chatWidgetContainer.style.height = '480px'; chatWidgetContainer.style.backgroundColor = '#fff'; chatWidgetContainer.style.border = '1px solid #ccc'; chatWidgetContainer.style.borderRadius = '4px'; chatWidgetContainer.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)'; chatWidgetContainer.style.fontFamily = 'Arial, sans-serif'; chatWidgetContainer.style.display = 'none'; // Hide the chat widget initially document.body.appendChild(chatWidgetContainer); // Create close button for the chat widget var closeButton = document.createElement('button'); closeButton.innerText = 'X'; closeButton.style.position = 'absolute'; closeButton.style.top = '10px'; closeButton.style.right = '10px'; closeButton.style.padding = '5px'; closeButton.style.backgroundColor = '#007bff'; closeButton.style.color = '#fff'; closeButton.style.border = 'none'; closeButton.style.borderRadius = '4px'; closeButton.style.cursor = 'pointer'; chatWidgetContainer.appendChild(closeButton); var chatWindow = document.createElement('div'); chatWindow.style.height = '400px'; chatWindow.style.overflowY = 'auto'; chatWindow.style.padding = '10px'; chatWidgetContainer.appendChild(chatWindow); var inputField = document.createElement('input'); inputField.type = 'text'; inputField.className = 'input-field'; inputField.placeholder = 'Type your message'; inputField.style.width = '100%'; inputField.style.padding = '5px'; inputField.style.border = '1px solid #ccc'; inputField.style.borderRadius = '4px'; chatWidgetContainer.appendChild(inputField); var isTyping = false; inputField.addEventListener('input', function() { if (!isTyping) { isTyping = true; sendTypingNotification(true); } }); var typingTimer; inputField.addEventListener('input', function() { clearTimeout(typingTimer); typingTimer = setTimeout(function() { if (isTyping) { isTyping = false; sendTypingNotification(false); } }, 5000); // Adjust the delay as needed }); function sendTypingNotification(isTyping) { // Perform an asynchronous request to the server to send the typing status // You can use the fetch API or other AJAX techniques // Example using fetch API: fetch('https://' + chaterboxsiteurl + '/typing-notification/?widgetid=123&session=' + encodeURIComponent(getCookie('chaterbox')) + '&it=' + isTyping, { method: 'POST', body: JSON.stringify({ isTyping: isTyping }), headers: { 'Content-Type': 'application/json' } }) .then(response => { // Handle the response from the server if needed console.log('Typing notification sent to server'); }) .catch(error => { // Handle any errors that occurred during the request console.error('Error sending typing notification:', error); }); } var sendButton = document.createElement('button'); sendButton.innerText = 'Send'; sendButton.className = 'send-button'; sendButton.style.width = '100%'; sendButton.style.padding = '10px'; sendButton.style.backgroundColor = '#007bff'; sendButton.style.color = '#fff'; sendButton.style.border = 'none'; sendButton.style.borderRadius = '4px'; sendButton.style.cursor = 'pointer'; chatWidgetContainer.appendChild(sendButton); // Event listener for close button click closeButton.addEventListener('click', toggleChatWidget); // Toggle show/hide functionality function toggleChatWidget() { receiveMessageFromServer(); if (chatWidgetContainer.style.display === 'none') { chatWidgetContainer.style.display = 'block'; chatToggleButton.style.display = 'none'; postChatWindowStatus(true); } else { chatWidgetContainer.style.display = 'none'; chatToggleButton.style.display = 'block'; postChatWindowStatus(false); } } // Function to send a message to the server // Function to send a message to the server function sendMessageToServer(message) { // Perform an asynchronous request to your server here // You can use the fetch API or other AJAX techniques to send the message // Example using fetch API: fetch('https://' + chaterboxsiteurl + '/chat/?widgetid=123&session=' + encodeURIComponent(getCookie('chaterbox')), { method: 'POST', body: JSON.stringify({ type: 'user', message: message }), headers: { 'Content-Type': 'application/json' } }) .then(response => { receiveMessageFromServer(); // Handle the response from the server if needed // For example, you can check if the message was successfully sent console.log('Message sent to server'); }) .catch(error => { // Handle any errors that occurred during the request console.error('Error sending message to server:', error); }); } // Function to receive messages from the server function receiveMessageFromServer() { // Perform an asynchronous request to your server here // You can use the fetch API or other AJAX techniques to receive messages // Example using fetch API: fetch('https://' + chaterboxsiteurl + '/chat/?widgetid=123&session=' + encodeURIComponent(getCookie('chaterbox'))) .then(response => response.json()) .then(data => { // Process the received messages from the server // For example, you can iterate over the messages and add them to the chat window chatWindow.innerHTML = ''; data.messages.forEach(message => { addMessage(message); }); extendCookieExpiration("chaterbox", 365); // Extend the expiration of "chaterbox" cookie chatWindow.scrollTop = chatWindow.scrollHeight; }) .catch(error => { // Handle any errors that occurred during the request console.error('Error receiving messages from server:', error); }); } // Function to add a new message to the chat window function addMessage(messageData) { var newMessage = document.createElement('div'); newMessage.textContent = messageData.message; //changed from message to messageData.text // Add CSS styles based on the message type if (messageData.type === 'user') { newMessage.style.textAlign = 'left'; newMessage.style.backgroundColor = '#e8e8e8'; newMessage.style.marginBottom = '10px'; newMessage.style.padding = '10px'; newMessage.style.borderRadius = '4px'; } else if (messageData.type === 'agent') { newMessage.style.textAlign = 'right'; newMessage.style.backgroundColor = '#007bff'; newMessage.style.color = '#fff'; newMessage.style.marginBottom = '10px'; newMessage.style.padding = '10px'; newMessage.style.borderRadius = '4px'; } chatWindow.appendChild(newMessage); } // Event listener for send button click sendButton.addEventListener('click', function() { var message = inputField.value; sendMessageToServer(message); inputField.value = ''; }); // Event listener for pressing Enter key in input field inputField.addEventListener('keydown', function(event) { if (event.keyCode === 13) { event.preventDefault(); sendButton.click(); } }); // Event listener for toggling chat widget visibility document.addEventListener('keydown', function(event) { if (event.key === 'Escape') { toggleChatWidget(); } }); chatToggleButton.addEventListener('click', toggleChatWidget); function sendCurrentPageDataToServer() { var currentPageData = { url: window.location.href, title: document.title, UA: navigator.userAgent }; fetch('https://' + chaterboxsiteurl + '/current-page/?widgetid=123&session=' + encodeURIComponent(getCookie('chaterbox')), { method: 'POST', body: JSON.stringify(currentPageData), headers: { 'Content-Type': 'application/json' } }) .then(response => { // Handle the response from the server if needed console.log('Current page data sent to server'); }) .catch(error => { // Handle any errors that occurred during the request console.error('Error sending current page data:', error); }); } function postChatWindowStatus(isOpen) { const endpointUrl = 'https://' + chaterboxsiteurl + '/chat-window-status/?widgetid=123&session=' + encodeURIComponent(getCookie('chaterbox')) + '&status=' +isOpen; // Prepare the request payload const payload = { isOpen: isOpen, session: getCookie('chaterbox') }; // Send the API request fetch(endpointUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }) .then(response => { // Handle the response from the server if needed console.log('Chat window status posted:', isOpen); }) .catch(error => { // Handle any errors that occurred during the request console.error('Error posting chat window status:', error); }); } // Periodically receive messages from the server setInterval(receiveMessageFromServer, 10000); // Adjust the interval as needed setInterval(sendCurrentPageDataToServer, 10000); // Adjust the interval as needed function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var 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; } function extendCookieExpiration(cookieName, days) { var date = new Date(); date.setTime(date.getTime() + ((days*24*60*60*1000))); // hours in milliseconds var cookie = getCookie(cookieName); if (cookie) { //document.cookie = cookieName + "=" + cookie + "; expires=" + date.toUTCString() + "; secure=true; SameSite=Lax"; } } if (getCookie("chaterbox") == null) { var date = new Date(); setCookie("chaterbox", date.getTime(), 365); }