AI Engine Persistent Popup

Click to refresh the page!

Click to open a new tab!

This JavaScript will keep your chatbot open as the user navigates your website. Not only that, but it’ll make sure the conversation is up to date on all tabs.

That way if the user has many tabs open, for example of product pages, the bot will have the latest history even when switching between them.

document.addEventListener('DOMContentLoaded', () => {
    const maxWaitTime = 3000; // 3 seconds
    const startTime = Date.now();

    const getCookie = name => document.cookie.split('; ').find(row => row.startsWith(name + '='))?.split('=')[1];

    const initializeWhenReady = () => {
        const chatWindow = document.querySelector('.mwai-window');
        if (chatWindow) {
            const openWindow = () => {
                const iconElement = chatWindow.querySelector('.mwai-icon');
                if (iconElement && !chatWindow.classList.contains('mwai-open')) {
                    iconElement.click();
                }
            };

            if (getCookie('mwai_window_open') === 'true') {
                let attempts = 0;
                const intervalId = setInterval(() => {
                    if (chatWindow.classList.contains('mwai-open')) {
                        clearInterval(intervalId);
                    } else if (++attempts >= 10) {
                        clearInterval(intervalId);
                    } else {
                        openWindow();
                    }
                }, 50);
            }

            new MutationObserver(() => {
                const isOpen = chatWindow.classList.contains('mwai-open');
                document.cookie = `mwai_window_open=${isOpen}; path=/; SameSite=Strict`;
            }).observe(chatWindow, { attributes: true, attributeFilter: ['class'] });

        } else if (Date.now() - startTime < maxWaitTime) {
            requestAnimationFrame(initializeWhenReady);
        }
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                // get bot ID
                const botId = chatWindow ? chatWindow.id.replace('mwai-chatbot-', '') : '';
                if (!botId) return;
                var context = localStorage.getItem('mwai-chat-' + botId);
                if (!context) return;
                var context = JSON.parse(context);
                if (!context) return;
                const chatbot = MwaiAPI.getChatbot(botId);
                if (!chatbot) return;
                chatbot.setContext(context);
                console.log('Restored latest context for bot', botId);
            }
        });
    };

    initializeWhenReady();
}, true);

Let’s enhance your business! I can help you develop custom AI engine extensions or broader AI strategies.

Contact me.

Leave a Reply

Your email address will not be published. Required fields are marked *