I had a task to add a Google Analytics ID to the user profile in LiveChat. We wanted to be able to match up the person we were chatting to with the analytics data in Google.

This looked really simple according to their docs. You can just use the following function:

1LiveChatWidget.call("set_session_variables", {
2 username: "john.doe",
3 cart_value: "450",
4 "order date": "05/21/2019",
5});
Copied!

What their docs failed to mention, and caused hours of headaches trying to debug a race condition, is that this function needs to be invoked as part of the On Ready callback. If you update the session variables once the chat has started, they won’t get saved. I had further complexity due to LiveChat being loaded by GTM, so I needed to use a MutationObserver to listen to the node being added to the DOM, before initialising the On Ready callback.

Here’s the full code for my solution:

1function onReady(data) {
2 // Replace this object with an object of variables you need to push into LiveChat
3 const customVariables = { googleClientId: 'ID' };
4 LiveChatWidget.call("set_session_variables", customVariables);
5}
6 
7// Select the node that will be observed for mutations
8const liveChatMutationObserverTargetNode = document.body;
9 
10// Options for the observer (which mutations to observe)
11const liveChatMutationObserverConfig = { childList: true, subtree: true };
12 
13// Callback function to execute when mutations are observed
14const liveChatMutationObserverCallback = function(mutationsList, observer) {
15 for (let mutation of mutationsList) {
16 if (mutation.type === 'childList') {
17 let addedNodes = mutation.addedNodes;
18 // Loop through all added nodes
19 addedNodes.forEach(function(node) {
20 if(node.id === 'chat-widget-container') {
21 // Element with ID 'chat-widget-container' has been added
22 console.log('Chat widget added to the DOM');
23 
24 if (typeof LiveChatWidget !== 'undefined' && typeof LiveChatWidget.on === 'function') {
25 LiveChatWidget.on('ready', onReady)
26 }
27 
28 // Optional: Disconnect the observer after the element is found
29 observer.disconnect();
30 }
31 });
32 }
33 }
34};
35 
36// Create an instance of the MutationObserver
37const liveChatMutationObserver = new MutationObserver(liveChatMutationObserverCallback);
38 
39// Start observing the target node for configured mutations
40liveChatMutationObserver.observe(liveChatMutationObserverTargetNode, liveChatMutationObserverConfig);
Copied!

Hopefully, this code can help others overcome any similar problems and save hours of debugging when working with LiveChat.