Tag manager

Ability to track clicks with tag manager

1 Like

Hi there @user13629 :wave:

Great news - we’ve got a solution! To track clicks on WhatsApp Chat widget via GTM, please add this code to the Custom JS field on the Appearance tab of your widget’s settings:


function sendAnalyticsEvent(config) {
  if (typeof ga !== "undefined") {
    ga('send', 'event', {
      eventAction: config.action,
      eventCategory: config.category,
      eventLabel: config.label
    });
  }
  if (typeof gtag !== "undefined") {
    gtag('event', config.action, {
      'event_category': config.category,
      'event_label': config.label
    });
  }
}
function rafAsync() {
  return new Promise(resolve => {
    requestAnimationFrame(resolve);
  });
}
function checkElement(selector) {
  if (document.querySelector(selector) === null) {
    return rafAsync().then(() => checkElement(selector));
  } else {
    return Promise.resolve(true);
  }
}

checkElement('[class*="Bubble__BubbleComponent"]')
  .then(() => {
    const addClickEvent = (el, label) => el.addEventListener('click', () => {
        sendAnalyticsEvent({
          action: 'click',
          category: 'Elfsight Chat Widget',
          label: label
        });
      });
    const clicker = (el, label, all = false) => {
      const addClickWithLabel = (el) => addClickEvent(el, label);
      
      if (all) {
        [...document.querySelectorAll(el)].forEach(addClickWithLabel);
      } else {
        addClickWithLabel(document.querySelector(el));
      }
    };

    clicker('[class*="Bubble__BubbleComponent"]', 'Open/Close Chat Widget');
    clicker('[class*="DefaultButton__DefaultButtonComponent-sc"]', 'Click Start Chat Button', true);
  });

Check it out and let me know how it worked :wink: