DEV Community

Joe Bailey
Joe Bailey

Posted on

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",
});
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay