Up until today, everyone I know has struggled to capture a Google Analytics event on redirect links. We’ve all had to come up with hacks and workarounds to ensure that the initial landing page is tracked. Today I finally figured out a solution that works. Google analytics now offers a callback event which lets you fire the redirect (or any custom functionality after the main tracking event fires.

The snippet to add after the Google analytics tracking code setup is below:

ga('send', 'pageview', {
'page': '/my-new-page',
'hitCallback': function() {
window.location.replace = "[new url]";
}
});

 

View Comments
  • Hi Greg, can this be implemented with gtm also as I have several tags I need to fire prior to the redirect?

    • Hi Lee,

      I haven’t worked with the GTM product but looking over the docs, I think this still would work since you can call GTM through Javascript and Google Universal Analytics are a part of the suite. I’ll try to explore further and come up with a sample for you.

  • Hi Greg, Im using this code for analytics : ga(‘send’, ‘event’, ‘agentWebsiteClick’, ‘clicked’); . How can I add the callback function to this. I’m unable to do so. Thank you.

    • Hi Aatif,

      This should do what you need:

      ga(‘send’, ‘event’, {
      ‘agentWebsiteClick’: ‘clicked’,
      ‘hitCallback’: function() {
      window.location.replace = “[new url]”;
      }
      });

      There’s also a more detailed ga event that you can wire up:
      ga(‘send’, ‘event’, {
      ‘eventCategory’: ‘category’, //required
      ‘eventAction’: ‘clicked’, //required
      ‘eventLabel’: ‘agentWebsiteClick’,
      ‘eventValue’: 1,
      ‘hitCallback’: function() {
      console.log(‘Sent!!’);
      //callback function
      },
      ‘hitCallbackFail’ : function () {
      console.log(“Unable to send Google Analytics data”);
      //callback function
      }

Leave a Reply to Lee
Cancel Reply