How to add Custom Variables to LiveChat

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:

LiveChatWidget.call("set_session_variables", {
  username: "john.doe",
  cart_value: "450",
  "order date": "05/21/2019",
});

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:

function onReady(data) {
  // Replace this object with an object of variables you need to push into LiveChat
  const customVariables = { googleClientId: 'ID' };
  LiveChatWidget.call("set_session_variables", customVariables);
}

// Select the node that will be observed for mutations
const liveChatMutationObserverTargetNode = document.body;

// Options for the observer (which mutations to observe)
const liveChatMutationObserverConfig = { childList: true, subtree: true };

// Callback function to execute when mutations are observed
const liveChatMutationObserverCallback = function(mutationsList, observer) {
  for (let mutation of mutationsList) {
    if (mutation.type === 'childList') {
      let addedNodes = mutation.addedNodes;
      // Loop through all added nodes
      addedNodes.forEach(function(node) {
        if(node.id === 'chat-widget-container') {
          // Element with ID 'chat-widget-container' has been added
          console.log('Chat widget added to the DOM');

          if (typeof LiveChatWidget !== 'undefined' && typeof LiveChatWidget.on === 'function') {
            LiveChatWidget.on('ready', onReady)
          }

          // Optional: Disconnect the observer after the element is found
          observer.disconnect();
        }
      });
    }
  }
};

// Create an instance of the MutationObserver
const liveChatMutationObserver = new MutationObserver(liveChatMutationObserverCallback);

// Start observing the target node for configured mutations
liveChatMutationObserver.observe(liveChatMutationObserverTargetNode, liveChatMutationObserverConfig);

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