We use cookies to enhance your experience

We use essential cookies for site functionality and optional cookies like Google Analytics to understand how you use our site. You can customize your preferences at any time. Learn more

GA4 Analytics Integration

Track widget interactions and send events to Google Analytics 4

What You'll Learn

This guide explains how to enable GA4 tracking in your chat widget and set up your website to receive and process analytics events using Google Tag Manager or custom JavaScript.

Overview

The GA4 Analytics Integration allows your chat widget to send user interaction events to your website's analytics platform. Events are transmitted securely using the window.postMessage() API, which your parent website can listen for and forward to Google Analytics 4 or Google Tag Manager.

This integration is completely optional and disabled by default. When enabled, you can track important engagement metrics like widget opens, session starts, and user interactions.

Enabling Analytics in Your Widget

Step 1: Open the Analytics Panel

  1. Go to your widget editor
  2. Click on the "Analytics" tab in the sidebar
  3. Toggle "Enable" to turn on GA4 tracking

Step 2: Configure Event Parameters

Configure the department and chat type parameters that will be sent with all events:

  • Department - Select which department users are chatting with (sales, service, parts, other)
  • Chat Type - Select the communication method (chat, text, DR)

Step 3: Configure Tracked Events

Choose which events you want to track. Each event can be individually enabled or disabled:

  • Widget Impression - Fires once when widget loads on page
  • Widget Opened - Fires every time a user clicks to open chat
  • Session Started - Fires when a user sends their first message
  • Every Message - Fires each time user or agent sends a message
  • Lead Submitted - Fires when post-chat form is submitted
  • Widget Closed - Fires when a user closes the chat window

Step 4: Save Your Changes

After configuring your analytics settings, save your widget. The tracking will be active immediately for all embedded instances of your widget.

Understanding the Event Format

Message Structure

Every analytics event sent from the widget follows this standardized structure:

Event Message Formatjson
{
  "event": "chat_widget_opened",
  "messageSource": "trusted-widget-vendor-events",
  "data": {
    "provider": "crowd-chat",
    "chatProfitCenter": "sales",
    "chatType": "chat",
    "chatSessionId": "session_123456",
    "widgetId": "your-widget-id"
  }
}
event:The unique event name identifying the user action
messageSource:Security identifier (always "trusted-widget-vendor-events")
data:Object containing event parameters and context

Available Events

chat_widget_impression

Fires once when the chat widget loads on the page. Use this to track widget visibility and reach.

Parameters: chatProfitCenter (optional), chatType (optional), chatSessionId (optional)

chat_widget_opened

Tracks when a user clicks to open the chat. Fires every time the widget is opened. Indicates intent to start engagement.

Required: chatProfitCenter, chatType | Optional: chatSessionId

chat_session_started

Tracks when a user sends their first message. Indicates the beginning of an actual conversation.

Required: chatProfitCenter, chatType | Optional: chatSessionId

chat_message

Fires each time a message is sent by either the user or the agent. Use chatMessageType parameter to differentiate.

Required: chatProfitCenter, chatType, chatSessionId, chatMessageType (user or agent)

chat_lead_submitted

Fires when a post-chat form is submitted. Captures high-value conversions and lead information.

Required: chatProfitCenter, chatType, chatSessionId, chatLeadId

chat_widget_closed

Tracks when a user closes the chat after interaction. Indicates completion of a chat session.

Required: chatProfitCenter, chatType, chatSessionId

Setting Up Your Website to Receive Events

Automatic Forwarding

The widget iframe loader now automatically forwards analytics events to your host page. If window.dataLayer (GTM) or window.gtag() (GA4) is detected, events are pushed automatically. You can also listen for chatwidgetpro:analytics:* DOM events for custom handling. The manual setup options below are only needed if you want to customize the forwarded data.

Option 1: Custom Google Tag Manager Setup (Advanced)

Google Tag Manager makes it easy to capture postMessage events without modifying your website's code.

Step 1: Create a Custom HTML Tag

In Google Tag Manager, create a new Custom HTML tag with this code:

GTM Custom HTML Tagjavascript
<script>
  window.addEventListener('message', function(event) {
    try {
      var data = JSON.parse(event.data);

      // Verify the message source for security
      if (data.messageSource === 'trusted-widget-vendor-events') {
        // Push to dataLayer
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
          'event': 'chat_widget_event',
          'eventCategory': 'Chat Widget',
          'eventAction': data.event,
          'eventLabel': data.data.provider,
          'chatProfitCenter': data.data.chatProfitCenter,
          'chatType': data.data.chatType,
          'chatSessionId': data.data.chatSessionId,
          'chatMessageType': data.data.chatMessageType,
          'chatLeadId': data.data.chatLeadId,
          'widgetId': data.data.widgetId
        });

        console.log('Chat widget event tracked:', data.event);
      }
    } catch (e) {
      // Not a valid JSON message, ignore
    }
  });
</script>
Step 2: Set Trigger

Set the trigger to fire on "All Pages" or specific pages where your widget is embedded.

Step 3: Create GA4 Event Tag

Create a new GA4 Event tag that fires when the custom event "chat_widget_event" is pushed to the dataLayer:

  • Tag Type: Google Analytics: GA4 Event
  • Event Name: Use variable {{eventAction}}
  • Add parameters: event_category, event_label, widget_id, session_id
  • Trigger: Custom Event - chat_widget_event

Option 2: Custom JavaScript Listener (Advanced)

If you're not using Google Tag Manager, you can add this JavaScript directly to your website:

Custom JavaScript Listenerjavascript
// Add this to your website's JavaScript
window.addEventListener('message', function(event) {
  try {
    const data = JSON.parse(event.data);

    // Verify the security identifier
    if (data.messageSource === 'trusted-widget-vendor-events') {
      // Send to Google Analytics 4
      if (typeof gtag !== 'undefined') {
        gtag('event', data.event, {
          'event_category': 'Chat Widget',
          'event_label': data.data.provider,
          'chat_profit_center': data.data.chatProfitCenter,
          'chat_type': data.data.chatType,
          'chat_session_id': data.data.chatSessionId,
          'chat_message_type': data.data.chatMessageType,
          'chat_lead_id': data.data.chatLeadId,
          'widget_id': data.data.widgetId
        });

        console.log('Chat widget event sent to GA4:', data.event);
      }
    }
  } catch (e) {
    // Not a valid JSON message or not from our widget
  }
});
This code should be placed after your Google Analytics initialization script and before the closing body tag.

Testing Your Integration

Verify Events Are Being Sent

  1. Open your browser's developer console (F12 or Cmd+Option+I)
  2. Navigate to the Console tab
  3. Interact with your chat widget (open it, send a message, close it)
  4. Look for console.log messages showing events being sent
You should see messages like "[Chat Widget] PostMessage Sent: chat_widget_opened" in the console.

Verify Events in Google Analytics

  1. Open Google Analytics 4
  2. Navigate to Reports → Realtime
  3. Interact with your widget while watching the Realtime report
  4. Look for your custom events appearing in the event stream

Debug with GTM Preview Mode

If you're using Google Tag Manager:

  1. Enable Preview mode in GTM
  2. Navigate to your website
  3. Interact with the widget
  4. Check the GTM debugger to see if your tags are firing correctly

Security Considerations

The messageSource identifier acts as a security validation key. Your listener should always verify this value matches exactly:

if (data.messageSource === 'trusted-widget-vendor-events') {
  // Safe to process this event
} else {
  // Ignore - not from ChatWidgetPro
}
Never skip the messageSource validation. This prevents malicious scripts from injecting fake analytics events into your tracking.

Best Practices

  • Always validate messageSource before processing events
  • Test in preview mode before deploying to production
  • Monitor your GA4 reports to ensure events are being tracked correctly
  • Use GTM for easier management - it's more flexible than hardcoded JavaScript
  • Only enable events you need to keep your analytics clean

Troubleshooting

Events not appearing in console

  • Verify analytics is enabled in your widget editor
  • Check that the specific event type is enabled
  • Make sure you're not in preview mode (analytics is disabled in preview)

Events in console but not in GA4

  • Verify your message listener is correctly implemented
  • Check that the messageSource validation is working
  • Use GTM Preview mode to debug tag firing
  • Ensure your GA4 measurement ID is correct

Events tracking on wrong pages

  • Check your GTM tag triggers
  • Ensure the listener is only active on pages with the widget

Need Help?

If you're having trouble setting up GA4 tracking, check our community forums or contact support for assistance.
Hi and welcome! How can ChatWidgetPro help you ?