How to track HubSpot Live Chat using Google Tag Manager

black, white, and teal abstract painting

The following GTM setup guide will allow you to track a set of actions associated with Hubspot Live Chat and then send that info into Google Analytics as a new Event. This is great because then you can map a new Goal to any of the event actions below to track the success of the form but also to track incoming campaign traffic conversion rates.

Create a new HTML Tag and set the trigger to All Pages

<script>
window.addEventListener('message', function (e) {
    if (e.origin !== 'https://app.hubspot.com')
        return false;
    
    
    var hsData = JSON.parse(e.data);
    var hsAction = false;

    switch (hsData.type) {
        case 'closed-welcome-message':
            hsAction = 'Welcome Message Closed';
            break;
        case 'open-change':
            hsAction = (hsData.data) ? 'Chat Window Opened' : 'Chat Window Closed';
            break;
        case 'external-api-event':
            if (hsData.data.eventType = 'conversationStarted')
                hsAction = 'Conversation Started';
            break;
        default:
            hsAction = false;
            break;
    }

    if (hsAction) {
        window.dataLayer = window.dataLayer || [];
        try {
            window.dataLayer.push({
                'event': 'hs-chat-state-change',
                'hs-chat-state-change': {
                    'action': hsAction
                }
            });

        } catch (e) {
            console.warn('Datalayer push error: ' + e);
        }
    }
});
</script>

Create a new Trigger

nametrigger typevalue
CE – Hubspot – Live ChatCustom Evenths-chat-state-change

Create a new Custom Variable

Nametypevalue
EDLV – Hubspot – Live Chat – ActionData Layer Variablehs-chat-state-change.action

Create a new Google Analytics Tag

tag settingvalue
Tag NameGA – Event – Hubspot Live Chat
Track TypeEvent
CategoryKey Engagement
ActionHubspot Live Chat
Label{{EDLV – Hubspot – Live Chat – Action}}
TriggerCE – Hubspot – Live Chat

Give it a go, preview the changes and interact with your live chat widget. If you’re using a tool like Adswerve’s epic DataLayer Inspector, you’ll be able to monitor the actions within your browser console. Otherwise, head over to your Real Time reporting in Google Analytics to view the Events.

Warning

– Always test scripts you find on the internet outside of your live environment

– This script is designed to not fire if it can’t see any Hubspot scripts so if you can’t see anything happening on your page, ensure Hubspot is actually firing

– Make sure you notify anybody who manages the other end of HS Live Chat that you’re testing things before hammering the live chat systems