Skip to content

Instantly share code, notes, and snippets.

@Knogobert
Created March 18, 2019 13:00
Show Gist options
  • Save Knogobert/765e06e5a0e71fab0993aa58cb707639 to your computer and use it in GitHub Desktop.
Save Knogobert/765e06e5a0e71fab0993aa58cb707639 to your computer and use it in GitHub Desktop.
JS — Freshchat script for Google Tag Manager (GTM) with events for Google Analytics (GA)
<script>
var messagesSent = 0;
window.fcSettings = {
token: "YOUR_FC_TOKEN",
host: "https://wchat.freshchat.com",
onInit: function() {
if (window.dataLayer !== undefined) {
window.fcWidget.on("widget:loaded", function (resp) {
window.fcWidget.on("widget:opened", function (resp) {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'Widget Open', eventLabel: window.location.href });
});
window.fcWidget.on("widget:closed", function (resp) {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'Widget Close', eventLabel: window.location.href });
});
window.fcWidget.on('message:received', function (resp) {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'Received', eventLabel: window.location.href });
});
window.fcWidget.on('message:sent', function (resp) {
if (messagesSent === 0) {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'Sent first chat', eventLabel: window.location.href });
}
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'Sent', eventLabel: window.location.href });
messagesSent++;
});
window.fcWidget.on('user:statechange', function (resp) {
if (resp && resp.data && resp.data.userState === "created") {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'User Create', eventLabel: window.location.href });
}
if (resp && resp.data && resp.data.userState === "loaded") {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'User Loaded', eventLabel: window.location.href });
}
if (resp && resp.data && resp.data.userState === "identified") {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'User Identified', eventLabel: window.location.href });
}
if (resp && resp.data && resp.data.userState === "restored") {
window.dataLayer.push({ event: "GeneralEvent", eventCategory: "freshchat", eventAction: 'User Restored', eventLabel: window.location.href });
}
});
});
}
else {
console.log('Freshchat can’t use Google Tag Manager');
}
}
};
</script>
<script src="https://wchat.freshchat.com/js/widget.js" async></script>
@Knogobert
Copy link
Author

Add to your GTM as 'Custom HTML' and add a custom GeneralEvent Tag that it can use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment