Google Analytics send event callback function

前端 未结 3 902
面向向阳花
面向向阳花 2020-12-08 14:57

I\'m trying to send an event to Google Analytics after a user is registered and before he\'s redirected. I\'m using Google Tag Manager and universal js.

3条回答
  •  臣服心动
    2020-12-08 15:36

    Finally got it. It's pretty complicated and not described in docs. In my case I use Google Tag Manager, so there some workarounds I had to make to get successfully fire an event and get callback.

    First, we have to get ClientId, which is required with any event sent to Google servers. Actually it's kept in cookies, but Google does not recommend to take it directly from there.

    Here is how Google recommends to get it, but this will not work if you are using Google Tag Manager.

     ga(function(tracker) {
           var clientId = tracker.get('clientId');
     });
    

    Instead, you have to get ClientId from getAll method.

     var clientId = ga.getAll()[0].get('clientId');
    

    After, you have to create new tracker

        ga('create', 'UA-XXX-YYY', {
            'clientId': clientId
        });
    

    And after that we can send an event:

     ga('send', 'event', {
       'eventCategory': 'YOUR Category Name', //required
       'eventAction': 'YOUR Action name', //required
       'eventLabel': 'YOUR Label',
       'eventValue': 1,
       'hitCallback': function() {
           console.log('Sent!!');
          //callback function
        },
       'hitCallbackFail' : function () {
          console.log("Unable to send Google Analytics data");
          //callback function
       }
    });
    

提交回复
热议问题