Four Killer Uses For HitCallback You Need To Be Using... RIGHT NOW!
Firing tags in Google Tag Manager (GTM) in the correct order can be, at times, difficult. We always want our important tags to fire first, and often we have specific tags that should fire before or after another tag. GTM introduced a feature called Tag firing priority awhile ago, but that just rearranged when tags would start to load, not necessarily waiting for anything to complete in between.
Then came Tag Sequencing inside of Google Tag Manager, which is extremely helpful. Simo Ahava has a nice writeup of tag sequencing on his blog, and the feature has been an excellent addition to our arsenal of tools.
There’s another great feature that we can use, specifically when dealing with Google Analytics tags, that lets us wait for the Google Analytics command to finish and then executes something else immediately after. Imagine a swimming relay during the Olympics, where one swimmer waits patiently on the block for Michael Phelps to finish his leg of the relay. The next action cannot start until the first one completes.
Behold the hitCallback
The hitCallback is a whizzbang feature of Google Analytics (GA). It allows you to execute code after a hit is successfully sent to GA. One of the benefits of using the hitCallback is that it will work with on-page code, as well as in Google Tag Manager. In GTM, the hitCallback is configured in the ‘fields to set’ section of a GA tag.
Per GA’s Developer documentation the callback executes a function on success. In GTM, we can achieve this using a custom JavaScript variable that executes a function that returns another function we want to be run on success. It looks something like this:
function() { return function() { ... // insert code here } }
In the past, this has been handy, especially for lead generation sites. Whenever a user submits a form, the POST process is interrupted, the GA hit is sent and then the hitCallback allows the process to continue. The inner workings of this process can be found here.
Today, form submits can easily be handled using Google Tag Manager and its wait for tags and check validation.
Yet, that still leaves us with hitCallback. How else can we take advantage this great feature? (I’m so glad you asked!) One thing we can do is write or clear persistent data.
Get ready to dive in, below are a few examples:
1. Fetch and Send the Client ID
(Courtesy Dan Wilkerson)
Getting the Client ID (CID) into GA can prove very beneficial in troubleshooting and analysis. However, if you try to access the Client ID before its been created and stored, then you won’t get any information.
We can use hitCallback to 1) wait until the pageview has been sent and then 2) send an event straight after the pageview sends. This way, if they are a new user we will receive their client ID immediately after the tracker is set and the pageview sends.
function() { return function() { if (!{{JS - Client ID}}) { dataLayer.push({ 'event': 'storeCid' }); } }; }
With this method we send a GTM event (storeCid) that triggers a GA Event tag (lots of different definitions of the word “event”, I know) that includes the CID as both a custom dimension and as an event label.
Here’s our client ID JavaScript:
// Because no tracker has been instantiated yet in certain situations, we parse the // _ga cookie directly function () { return {{Cookie - _ga}}.match(/\d+\.\d+$/)[0]; }
2. Establish Membership Values
Have a loyalty or rewards member program? Maybe you want to know when a user is logged in? Whenever some successfully signs up or signs in, we can establish a cookie that successfully registers them accordingly. Here, we are using LunaMetrics’ Cookie Management GTM Recipe to set these values:
function() { return function() { setStatus_('rewardsMember', {{memberLevel}}); // Sets Rewards Member Lever (Silver, Gold, etc.) setStatus_('loggedInUser', {{logInStatus}}); // Sets the Boolean value of logged in status function setStatus_(cookieName, status) { if(status) { dataLayer.push({ 'event': 'setCookie', 'attributes': { 'cookieName': cookieName, 'cookieValue': status, 'cookieDomain': 'www.myhostname.com', 'cookiePath': '/', 'cookieExpires': 730 // Number of days - provide a fraction for periods less than 24 hours } }); } } } }
We leverage hitCallback to initiate this dataLayer push after each successful GA pageview. We can then pick up this value as a 1st party cookie variable in GTM and (re)use this value as they return to the site.
3. Null Content Metadata
Infinite scroll content makes for great user engagement, but can prove problematic especially when using the data layer for sending contextual data to GA via GTM. Using data layer pushes will update prior information, but can allow preexisting values to carry over to the next pageview. If a custom dimension is set from the data layer on one hit, but you don’t want it to be set necessarily on subsequent hits, than you might need something like this.
For instance, suddenly an Author is given credit for content they didn’t write! Why not clear out those values using hitCallback?
function() { return function() { dataLayer.push({ 'event' : 'gtm.dlReset', 'author' : undefined, 'publishDate' : undefined, }); } }
This way the ‘slate’ is clean before the next hit to be sent to GA. This will keep your content meta data fresh as each article loads!
4. Clean up GA Events/Virtual Pageviews
Sometimes, we modify existing JavaScript on the page to create data layer pushes to trigger GA Events in GTM. This process can be handy and speed up migration, but doesn’t always benefit from the full functionality of using Google Tag Manager.
Also, just like above, relying on data layer variables can prove problematic if they’re not set with regularity. We can also clear these values for GA events and virtual page paths being sent through data layer pushes.
function() { return function() { dataLayer.push({ 'event' : 'gtm.dlReset', 'category' : undefined, 'action' : undefined, 'label' : undefined, 'value' : undefined, 'nonInteraction' : undefined, 'virtualPagePath' : undefined }); } }
Beyond having multiple events on the page, this could be very beneficial for single page applications provided they are using the data layer and ‘fields to set’ to report changes in page path.
In the end, hitCallback can be leveraged in some interesting ways that complement the existing Tag sequencing and tag firing priority features inside of GTM.