
January 10, 2018
Track Comments with Google Tag Manager: Everything from A to Z
If you’re running a blog, forum, or another website where readers can express their opinions and discuss, you should definitely measure comment submissions. Thanks to Google Tag Manager, that is possible and you can send that data to other web analytics tools, like Google Analytics.
By tracking comments you’ll be able to see which content drives the engagement the most and therefore better understand what your readers like or dislike because pageviews is not necessarily a good sign of quality likable content.
In this comprehensive guide, I’ll show you how to track comments with Google Tag Manager and send that data to Google Analytics as events.
Note: this blog post teaches how to track events with Universal Analytics. If you want to get familiar with event tracking in Google Analytics 4, you can also refer to this blog post.

Table of contents
- The Variety of Comment Boxes
- Tag + Trigger
- Which Comment Tracking Method Should You Choose?
- #1. Ready-made Solution for Popular Comment Boxes
- #2. The Default Form Submission Trigger in GTM
- #3. AJAX Comment Box Tracking
- #4. Data Layer Events
- #5. Other methods how to track comments with Google Tag Manager
- Conclusion
The variety of comment boxes
Just like with form tracking, there are way too many different types/solutions of comment boxes. Some of them refresh the page, while others just display a success message without doing much to the page itself. Some comment boxes are developed by well-known companies, like Facebook or Disqus, while others were created by a freelancer you (or your client) hired.
As a result, there is no “one method to track them all”. You’ll need to analyze how comment box works on your website and use one of the tracking methods I’ve described in this guide.
Before we continue: tag + trigger
You are probably already familiar with the main Google Tag Manager concept: every interaction you want to track needs a tag and a trigger. If you want to track all comment submissions with Google Analytics, you’ll need to create a Google Analytics Tag and a Trigger (rule) when that tag must fire. Creating a tag is the easy part of this process. Let’s make one, you’ll need it in next chapters of this guide:
- Go to Tags
- Press New button
- In Tag Configuration choose Universal Analytics:
- Track Type – Event
- Event Category – Comment submission (feel free to choose another appropriate title)
- Event Action – {{Page URL}}.
- Event Label – This field is optional so we’ll leave it empty this time. P.S. Feel free to choose other values for an event category, action and label.
- Assign Google Analytics Settings Variable (which contains tracking ID, e.g. UA-XXXXXX-XX).
- Leave other fields as they are.
- Leave the Triggering part empty (for now) and click Save. We’ll get back to it later. 80% of this blog post is dedicated to various types of triggers you can make use of. The choice of trigger type depends on the way a comment box was developed.
Which comment tracking method should you choose?
I’ve created a similar flowchart in another blog post, how to track forms with Google Tag Manager, but with some modifications. Since it received a lot of positive feedback, you can be assured of getting the best results quite quickly.
Before we dive into the pool triggers, we’ll need to inspect a comment box and decide which technique fits our needs the best. I have prepared a flow scheme which should help you choose the right method how to track comments with Google Tag Manager.
I am sure that some parts of that scheme might look vague. Continue reading and everything will become much clearer.
#1. Ready-made solutions for popular comment boxes
Chances are that you’re using a well-known comment plugin. Why is it good news? It’s highly possible that there’s a ready-made tracking solution published online with a step-by-step tutorial. Two of the most known comment plugins (from my experience) are Facebook Comments and Disqus Comments.
How do you know which provider has developed comment boxes you’re using? There are several options:
- Maybe you already know it because you’ve installed a plugin on your WordPress site (or whatever content management system are you using)?
- You could ask a developer, maybe he/she knows.
- Another option is to look for a logo or some other signs of the brand. For example, Disqus comment box contains a logo at the bottom right corner.
- The last option is a bit technical. Try inspecting the comment box with browser’s developer tools. There might some signs of what company developed this comment box. For example, here’s what I found after doing a right-click on Disqus Comment box and looking for some names or links.
- No luck? You’re probably using a custom-made comments solution. In that case, skip this chapter and move to the next one.
If you managed to identify the brand of the comment box, google for ready-made GTM solutions and you should find something.
If not, there are other tracking methods in this guide that you can find useful.
As of the moment of writing this blog post, I have published two blog posts on how to track comments with Google Tag Manager:
- Facebook comments
- Disqus comments.
To make your life easier, both guides (posted above) contain GTM Recipes, ready-made container templates. You can just download the file, import to GTM and start tracking comments within minutes.
#2. The default form submission trigger in GTM
You can call it whatever you want, but comment boxes are nothing else but forms, therefore you have to track them as forms. You should give a try to GTM’s built-in form listener.
Open a list of Variables in your GTM account. Under built-in variables, click Configure and enable all Form variables in the right sidebar (all changes are automatically saved).
Then open a list of all triggers (by clicking Triggers in the left sidebar). Create new trigger:
- Title – “All form submissions”.
- Trigger type – Form submission.
- Leave Wait for tags unchecked (for now). Later, you can set it to 2000 milliseconds, this means that the page will reload only 2 seconds after the form/comment box was submitted. 2000 milliseconds should be enough time for Google Analytics Event tag to fire.
- Click Check validation checkbox. Once this is checked, GTM will not fire the Trigger if the default action of the form (submit and redirect) is prevented. If left unchecked, the Trigger will go off whenever a submit event is registered (even when a form is submitted with errors (e.g. several required fields are left blank)).
- Fire on. In this example, I want to track all forms.
Now, let’s use GTM’s Preview and Debug mode to find out whether default form auto-event listener works for us. At the top-right corner of your Google Tag Manager account, click “Preview”.
Once the preview mode is enabled, navigate to the site where the comment box is embedded and you will see a debug console at the bottom of your browser showing detailed information about your tags, including their firing status and what data is being processed. This console window will appear only on your computer as you preview the site, and is not visible to your other website visitors. It should look something like this:
If you have already opened that page with the comment box but don’t see the GTM debug console, refresh the page. If you still face problems, I suggest reading this blog post, How To Fix GTM Preview and Debug Mode.
Let’s get back to how to track comments with Google Tag Manager. Fill in the comment box (try not to leave any fields blank):
- Hit the submit button. Did a gtm.formSubmit event appear in the Preview and Debug console? If not, then GTM’s Form auto-event listener will not work with this comment box and you should skip to next comment tracking option described in this guide.
- If gtm.formSubmit event did appear in Preview and debug console, then you should do another test – try leaving at least one required comment field empty (e.g. name) and submit the comment again. This way you’ll imitate an error in your comment box:
- If gtm.formSubmit event fired once again, then you should check other comment tracking options mentioned in this blog post. Why? In your case, the trigger fires always, regardless of whether the comment was successfully submitted or not. You don’t want to track false submissions, do you?
- If gtm.formSubmit event did not fire – that’s great! It means that GTM will track only those comment submissions which were successfully completed (and this is exactly what you need).
Great! We’ve identified that our comment box can be tracked with GTM’s built-in form listener. Let’s create a trigger specifically for that type of form, i.e. comment box. Remember gtm.formSubmit event that was previously mentioned? Click on it (in Preview and Debug mode), then click Variables.
Then scroll down and start looking for any Form variable that is unique for that comment box. Usually, comment boxes have a distinct Form Class (e.g. comment_box). Use that as a trigger condition. As you can see in the image below, I have submitted a comment (of which Form Class variable is comment_box).
Now, let’s use it in a trigger:
- Go to Triggers and click New
- Click Trigger configuration section and choose trigger type – Form submission
- Click Check validation and set the rule Page URL matches RegEx (.*). This rule means that this comment submission trigger will be available on all pages. If you want to make it accessible only on particular pages, you can add more specific rules, such as Page URL contains /post/ (it depends on the web addresses where your comment boxes are located).
- Then configure this trigger to fire only on some forms and enter the following rule: Form Classes equals comment_box. Contains operator is also fine.
- If you don’t see Form Classes variable – Enable it in the list of Built-in variables of Google Tag Manager.
- The value of form class may (and probably will) be different in your case (compared to my example).
Let’s test
- Assign this new trigger to Google Analytics Tag that you created at the beginning of this blog post.
- Open (or refresh) a Preview and Debug mode, refresh a web page with a form you want to track.
- Then fill in the comment box and submit – if Google Analytics Tag fired, that’s good news!

Wow! You still reading! Thanks for the dedication. If you feel a bit tired, you can always bookmark this guide how to track comments with Google Tag Manager and come back anytime later.
#3. AJAX comment box tracking
If you are reading this part, your custom-made comment box probably just refreshes itself and then displays “Your comment was successfully submitted” message without the actual page refresh. There’s a big chance that this comment box is using AJAX. I suggest skipping all the technical mumbo-jumbo here (since I am not a developer + I don’t think I am capable of clearly explaining how it works). The only thing here you should know is AJAX listener.
Lunametrics have published a code of an awesome AJAX listener and everyone can use for free. It listens to all AJAX events on a website and pushes them to the Data Layer. What does it mean? Well, you will be able to catch only those AJAX responses which contain the data of a successful comment submission.
Here’s the code of AJAX listener. Copy it and paste into a Custom HTML tag in Google Tag Manager.
<script id="gtm-jq-ajax-listen" type="text/javascript"> (function() { 'use strict'; var $; var n = 0; init(); function init(n) { // Ensure jQuery is available before anything if (typeof jQuery !== 'undefined') { // Define our $ shortcut locally $ = jQuery; bindToAjax(); // Check for up to 10 seconds } else if (n < 20) { n++; setTimeout(init, 500); } } function bindToAjax() { $(document).bind('ajaxComplete', function(evt, jqXhr, opts) { // Create a fake a element for magically simple URL parsing var fullUrl = document.createElement('a'); fullUrl.href = opts.url; // IE9+ strips the leading slash from a.pathname because who wants to get home on time Friday anyways var pathname = fullUrl.pathname[0] === '/' ? fullUrl.pathname : '/' + fullUrl.pathname; // Manually remove the leading question mark, if there is one var queryString = fullUrl.search[0] === '?' ? fullUrl.search.slice(1) : fullUrl.search; // Turn our params and headers into objects for easier reference var queryParameters = objMap(queryString, '&', '=', true); var headers = objMap(jqXhr.getAllResponseHeaders(), '\n', ':'); // Blindly push to the dataLayer because this fires within GTM dataLayer.push({ 'event': 'ajaxComplete', 'attributes': { // Return empty strings to prevent accidental inheritance of old data 'type': opts.type || '', 'url': fullUrl.href || '', 'queryParameters': queryParameters, 'pathname': pathname || '', 'hostname': fullUrl.hostname || '', 'protocol': fullUrl.protocol || '', 'fragment': fullUrl.hash || '', 'statusCode': jqXhr.status || '', 'statusText': jqXhr.statusText || '', 'headers': headers, 'timestamp': evt.timeStamp || '', 'contentType': opts.contentType || '', // Defer to jQuery's handling of the response 'response': (jqXhr.responseJSON || jqXhr.responseXML || jqXhr.responseText || '') } }); }); } function objMap(data, delim, spl, decode) { var obj = {}; // If one of our parameters is missing, return an empty object if (!data || !delim || !spl) { return {}; } var arr = data.split(delim); var i; if (arr) { for (i = 0; i < arr.length; i++) { // If the decode flag is present, URL decode the set var item = decode ? decodeURIComponent(arr[i]) : arr[i]; var pair = item.split(spl); var key = trim_(pair[0]); var value = trim_(pair[1]); if (key && value) { obj[key] = value; } } } return obj; } // Basic .trim() polyfill function trim_(str) { if (str) { return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } } })(); /* * v0.1.0 * Created by the Google Analytics consultants at http://www.lunametrics.com * Written by @notdanwilkerson * Documentation: http://www.lunametrics.com/blog/2015/08/27/ajax-event-listener-google-tag-manager/ * Licensed under the Creative Commons 4.0 Attribution Public License */ </script>
After you installed Lunametrics’ AJAX listener via Custom HTML Tag, check whether your comment box is using AJAX technology:
- Enable (or refresh) Preview and Debug mode.
- Refresh the web page with a comment box.
- Try submitting the comment (fill in all fields).
- Did the ajaxComplete event appear in the Preview and debug console?
- If yes, the comment box is using AJAX.
- If no, skip to the next chapter of this guide.
Oh, you’re still reading?! Let’s see what can we do with that AJAX comment box. Click ajaxComplete event in Preview and Debug mode, then click Data Layer:
It looks difficult for a non-developer, right? But it’s easier than you think. This is the data that was passed to the data layer after successful comment submission, each line is a separate dataLayer data point which can be used as a dataLayer variable in GTM. You should be looking for something which helps identify successful comment submission. Scroll down and look for “response”.
Let’s take a closer look at it. Can you see a message “This message has been successfully sent”? Bingo! We can use it as a trigger.
P.S. Some forms or comment boxes fire multiple AJAX requests, therefore you need to check both events in the Data Layer Tab and try to identify which one contains the information of successfully submitted comment.
First, let’s create a dataLayer variable in Google Tag Manager.
- Go to Variables
- Scroll down to User-Defined variable and hit New
- Click Variable configuration and choose variable type – Data Layer Variable
- Enter Data Layer Variable Name – attributes.response. Leave all other settings as they are.
- My recommendation for Title of this GTM variable is dlv – attributes.response (“dlv” stands for Data Layer Variable).
You’re probably guessing why I entered attributes.response as Data Layer Variable Name. Let’s take a closer look at Data Layer in Preview and Debug mode. In line 2, you can see the event name, ajaxComplete, that’s the same name which appears in Preview and Debug console’s left side. Then we see attributes which is an array of various data points (response is one of them).
So when we want to tell Google Tag Manager that we are interested in response’s value, we need to tell the exact path to that data. In our case, it’s attributes → response. Each level of the path must be separated with a dot → attributes.response. Another example: let’s say you’re interested in Server data (from that very exact AJAX response). In that case, Data Layer Variable’s Name should be attributes.headers.Server .
After we created an attributes.response Data Layer variable in Google Tag Manager, let’s debug. Refresh Preview and Debug mode and refresh the page where the AJAX comment box is. I am writing a blog post using a demo from this website (use Example 1). Fill in the comment and submit. Click the most recent ajaxComplete event in Preview and Debug console, then navigate to Variables tab and find your new variable dlv – attributes.response. If you did everything correctly, it should look like this:
That’s a message of the successfully submitted comment. If the value of that variable is undefined, then you should start looking for mistakes. The most common ones are typos in the variable name or inaccurately defined variable’s path. Some guys just try using response instead of attributes.response. If you’re still facing issues, read the guide How To Access Data In The Data Layer.
Now let’s create a trigger that fires when the event is ajaxComplete AND our new dataLayer variable contains text The message has been successfully sent.
- Go to Triggers and click New
- Choose Trigger Type – Custom Event. If you’re new to this, Custom event = Data Layer event. Lunametrics’ AJAX listener creates a Data Layer event (via dataLayer.push method) each time an AJAX request is made.
- Enter Event name – ajaxComplete
- This trigger should fire on Some Custom Events.
- Define a condition when the trigger will fire – dlv – attributes.response contains The message has been successfully sent.
Let’s test
- Assign this new trigger to Google Analytics Tag that you created in the beginning of this blog post.
- Open (or refresh) a Preview and Debug mode, refresh a web page with a comment box you want to track.
- Then fill in the AJAX comment box and submit. After successful submission, Google Analytics Tag should fire (it will be displayed in Preview and Debug mode. You can also check Google Analytics Real-time event reports).
Things to keep in mind when tracking AJAX comment boxes:
- The AJAX response of your comment submission will look different so try adjusting my tutorial to your situation.
- If developers change response’s data, your trigger will fail. Inform developers about your GTM implementation.
- If the page contains more than one AJAX comment box, try looking for more information in Data Layer which can help Google Tag Manager tell the difference between those comment boxes.

#4. Data layer events
Disclaimer: Although this method how to track comments with Google Tag Manager is more robust than method 3 (AJAX), I placed it as a No.4 option in this list for a reason. When other marketers approach me for a comment tracking advice, they’re looking forward to a solution when developer’s input can be avoided.
The slogan “Manage your marketing tags without help from developers” is one the main reasons why they started considering Google Tag Manager in the first place. This statement was among GTM’s key “selling” points when it was launched, so it’s no surprise marketers are expecting this to be 100% true, although you an I should know that in a lot of situations developer’s help is strongly advised. My position here is:
- If you have access to developers and Google Tag Manager’s Form listener isn’t working for you, I recommend using window.dataLayer.push method which I will describe in a moment.
- If you don’t have access to developers or they are super busy (and they probably are), then it’s okay to track with other techniques mentioned in this blog post. Just be aware, that other solutions have a bigger chance to break when developers make changes to a website you’re tracking. This especially applies to techniques mentioned in the following chapter – DOM scraping and Element Visibility Trigger.
I hope I made my point clear and we can continue.
As it was mentioned above, if standard Google Tag Manager Form listener does not work with your comment boxes, the next best thing is to ask the developer to implement a custom window.dataLayer.push() into the callback function which is invoked upon a successful comment submission. The piece of code could be something like:
<script> window.dataLayer.push({ 'event': 'commentSubmission', 'pageTitle': 'This is a page title' //this should be dynamically changed (based on the page the visitor is on) }); </script>
You’ll need to prepare a short but well-written and clear task for a developer:
- First, choose a name for the event. In the example, above I chose commentSubmission.
- Then think of any additional data you may need. Write those data points down and try categorizing them. In my example, I thought that it would be useful to know what was the title of the page where the comment was submitted.
- If a developer is new to dataLayer events and Google Tag Manager in general, hand them this link to the Data Layer guide. Explain to them that you need an event and (if possible) one additional variable pushed into the dataLayer after the successful comment submission. If you need, you can ask for more data to be passed.
- Remember: Do not ask a developer to pass any personal data if you’re working with GA. Google is strictly against PII (Personally Identifiable Information) stored in Google Analytics.
Done! After the developer implements window.dataLayer.push in all comment boxes, you should test it:
- Open Preview and Debug mode.
- Refresh the page with the comment box.
- Try submitting the comment:
- Leave at least one required field blank. In this case, dataLayer event must not be pushed.
- Fill in all fields and try submitting again. Did the event appear in Preview and debug console? It should look like this:
- Check whether all data is correctly pushed to dataLayer. Click commentSubmission event and then open Data Layer tab in Preview console. Data should look like this:
Setup variables and triggers in GTM. In my window.dataLayer.push example, there is one data point I’d like to use as a variable – pageTitle, so I need to include it to Google Tag Manager by creating a Data Layer variable.
Title: dlv – pageTitle
Variable type: Data Layer Variable
Data Layer Variable Name: pageTitle
Leave all other settings as they are
Now, let’s create a trigger. Go to Triggers and click New. Enter the following settings:
Trigger Type: Custom event
Event name: commentSubmission (it may differ depending on your situation. Just make sure you and your developer are using the same name).
This trigger fires on: All custom events. This means that all commentSubmission events will be tracked.
Let’s test
- Assign this new trigger to Google Analytics Tag that you created in the beginning of this blog post.
- Open (or refresh) a Preview and Debug mode, refresh a web page with a comment box you want to track.
- Then fill in the comment box and submit. After successful submission, Google Analytics Tag should fire (it will be displayed in Preview and Debug mode. You can also check Google Analytics Real-time event reports).
Tip: In this chapter, I’d recommend making few changes to Google Analytics Event Tag. In the beginning of this blog post I suggested creating a GA event tag with the following values:
- Form submission as Event Category
- {{Page URL}} as Event Action
- Empty Event Label.
Since we asked our developer to an additional variable via window.dataLayer.push, we can use this data and push it to GA. We could change:
- Event Category shoud remain the same, Comment submission
- Event Action – from {{Page URL}} to Page: {{dlv – pageTitle}}
- Set Event Label as {{Page URL}}
How will this event be displayed in Google Analytics event reports? Here’s an example:
- Event Category: Comment submission
- Event Action: Page: This is a page title
- Event Label: https://www.analyticsmania.com/mega-blog-post/
#5. Other solutions
I will not cover the following two methods in depth since they are not super reliable. Why? Because they heavily rely on your web page’s code structure. If developers are constantly updating the design of the page, adding new or removing old elements, you’re at risk that one day your trigger will stop working.
The worst part is that you won’t notice it on the same day. Sometimes we spot the issue of missing events only a week after the incident (or even later), and a week of missing data is a pretty significant loss for a marketer and web analyst. So you have to weigh the risks of using two following comment tracking methods:
- Element Visibility Trigger. It fires a Data Layer event when a particular element appears on the screen. In your case, it should be a “The comment was successfully submitted” message. Julian from MeasureSchool has published a video where he tracks success and error messages with this trigger.
- DOM Scraping. It’s a technique which checks the value of a particular web element. If a page reloads and the “Thank you” message appears, you can scrape the DOM in order to track it. You can find a more detailed guide here.
Conclusion: how to track comments with Google Tag Manager
Comment boxes are forms, therefore you have to treat them as forms. This means that there is no one single comment tracking method which applies to all comment boxes.
In this blog post, I’ve shared several most common techniques how to track comments with Google Tag Manager. First, you should inspect the comment box and see whether it’s developed by a well-known company, like Facebook or Disqus. In that case, there’s a big chance that you’ll find a ready-made comment tracking GTM solution.
No luck? Then you should try implementing the default Form Submission trigger in GTM or custom AJAX listener.
If you have access to developers, your most robust solution would be to ask them to fire a Data Layer event when a comment is successfully submitted. You could then catch that event and turn it into a trigger.
And I’ve also mentioned two risky comment tracking techniques, DOM scraping and element visibility trigger. But they should be treated as the last resort.
Do you have any questions regarding how to track comments with Google Tag Manager? Feel free to ask them in the comments section below. Happy tagging!

2 COMMENTS
Julius, great write up as always! I followed your steps to track forms using an AJAX listener and it worked like a charm! I really appreciate this information; organized and well thought out.
As for tracking blog comments, none of these solutions appear to work for me. I would like to reference the AJAX listener's variables but my comments don't seem to trigger it. My comments reload the page with an anchor URL (/hello-world#comment-2) but that doesn't trigger gtm.js event listener. Any advice on where I should look next would be greatly appreciated. Keep up the great work.
I actually solved the issue. The default form submission method worked! Thanks again for such a great write up.