UNPKG

messaggera

Version:

This script allows you to easily integrate a chat widget into your website. It dynamically loads the necessary resources and initializes the chat widget for your website. ## Installation

64 lines (53 loc) 2.27 kB
// messaggera.js (function() { const scriptElementId = 'messaggera-script'; const Messaggera = (websiteId, userData) => { console.log('messaggera script called'); if (!websiteId || typeof websiteId !== "string" || !/^[a-zA-Z0-9-_]+$/.test(websiteId)) { console.error("Invalid Website ID."); return; } if (userData) { if (typeof userData !== "object" || Array.isArray(userData) || Object.keys(userData).length === 0) { throw new Error("User data must be a non-empty object."); } const { id, email, ...optionalData } = userData; if (!id || typeof id !== "string") { throw new Error("The 'id' field is required and must be a string."); } if (!email || typeof email !== "string" || !/\S+@\S+\.\S+/.test(email)) { throw new Error("The 'email' field is required and must be a valid email address."); } window.$takiChat = []; window.$takiChat.push({ id, email, ...optionalData }); } window.WEBSITE_ID = websiteId; init(); }; const init = () => { if (isDocumentReady()) { addScriptToPage(); } else { document.addEventListener('readystatechange', handleReadyStateChange); window.addEventListener('load', addScriptToPage, { once: true }); } }; const handleReadyStateChange = () => { if (isDocumentReady()) { document.removeEventListener('readystatechange', handleReadyStateChange); addScriptToPage(); } }; const addScriptToPage = () => { if (document.getElementById(scriptElementId)) return; const script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.id = scriptElementId; script.src = `https://api.messaggera.com/api/owner/websites/${window.WEBSITE_ID}/check?q=${new Date().getTime()}`; document.head.appendChild(script); }; const isDocumentReady = () => document.readyState === 'complete' || document.readyState === 'interactive'; window.Messaggera = Messaggera; })();