Tracking click events in GTM for the Instagram Chat Widget

Hello,

I am trying to setup click tracking in GTM for the Instagram Chat Widget.
The code below works all the way until adding the click event listener.
However, the click listener doesn’t work.

Could you advise how to correct the code to make it work?

const SEND_MESSAGE_EVENT = 'chat_on_instagram';

const waitForElem = (selector) =>
  new Promise((resolve) => {
    console.log(`Waiting for element with selector: "${selector}"`);

    const element = document.querySelector(selector);
    if (element) {
      console.log(`Element found immediately: "${selector}"`);
      return resolve(element);
    }

    const observer = new MutationObserver(() => {
      const foundElem = document.querySelector(selector);
      if (foundElem) {
        console.log(`Element found via MutationObserver: "${selector}"`);
        observer.disconnect();
        resolve(foundElem);
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });

    console.warn(`Element with selector "${selector}" is not currently in the DOM.`);
  });

console.log('Script has been loaded successfully.');

if (typeof dataLayer !== 'undefined') {
  console.log('dataLayer is defined, proceeding...');
  
  waitForElem('[class*="ButtonContainer-sc"]')
    .then((sendMessageBtn) => {
      console.log('Button found, adding click listener...');
      sendMessageBtn.addEventListener('click', () => {
        console.log('Button clicked, pushing event to dataLayer...');
        dataLayer.push({ event: SEND_MESSAGE_EVENT });
        console.log(`Event "${SEND_MESSAGE_EVENT}" pushed to dataLayer`);
      });
    })
    .catch((err) => {
      console.error('Error waiting for element:', err.message);
    });
} else {
  console.error('dataLayer is not defined');
}
1 Like

Hi there, @Andrew_S :wave:

Here is the correct code that should be added 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
        });
    }
}

document.addEventListener('click', function (event) {
    const matchingItems = [
        {
            selector: '[class*="Bubble__BubbleComponent"]',
            label: 'Open/Close Chat Widget'
        },
        {
            selector: '[class*="ChatButton__DefaultButtonComponent-sc"]',
            label: 'Click Start Chat Button'
        },
    ];

    matchingItems.forEach((item) => {
        const match = event.target.closest(item.selector);

        if (match) {
            sendAnalyticsEvent({
                action: 'click',
                category: 'Elfsight Chat Widget',
                label: item.label
            });
        }
    });
});

Give it a shot and let me know if it worked :slightly_smiling_face:

1 Like

Doesn’t work unfortunately. :frowning:

The events aren’t being sent.
Is this supposed to work with the free widget or a paid plan is needed for Custom JS to work?

1 Like

@Andrew_S It should work for all plans. Could you please send me a link to the page, where your widget is installed?

Sent a DM, thank you!

1 Like

Could you please try to add this part to your website’s <head> and let me know if it worked?

<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-ID');
</script>