简体   繁体   中英

using Google Analytics hitCallback to send event before redirection to url

I tried to trigger an Google Analytics event when a specific link is clicked. To make sure the event is send before redirecting to the url, Google suggests to use the hitCallback function.

I tried it this way, but it won't work, because the link is immediately opened:

$('#service a').on("click",function(e){

  e.preventDefault();
  var title = $(this).data('title');
  var url   = $(this).attr('href');

  if ( typeof ga === 'function' ) {
    //console.log('started');
    ga('send', {
      hitType: 'event',
      eventCategory: 'header',
      eventAction: 'nav',
      eventLabel: 'service',
      eventValue: title,
      hitCallback : createFunctionWithTimeout(function() {
         //console.log('done')
         document.location = url;
      }, 100000)
    });
  }else{
    document.location = url;
  }

});

Here is the timeout function , suggested by Google:

function createFunctionWithTimeout(callback, opt_timeout) {
  var called = false;
    function fn() {
      if (!called) {
        called = true;
        callback();
      }
    }setTimeout(fn, 1000);
  return fn;
}

I would like to know why it isn't working, or if there is another way to achieve this.

Event value should be of integer type. Can you try hardcoding an integer to see if it works?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM