admin管理员组

文章数量:1391947

I am currently using analytics.js (the newer version of GA) and I am trying to track all types of events from my website, including when a user clicks on an anchor tag pointing to an external URL. I am currently using this setup:

 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics/analytics.js','ga');

  ga('create', 'UA-KEY-HERE', { 'alwaysSendReferrer': true, 'allowAnchor': true });

and I send the events when hitting a link like this:

$(document).on("click", ".anchor-class", function (event) {
    label = //get data from anchor element here ...  
    ga('send', 'event', 'Link Clicked', 'Click Details', label);;
    return;
    }
});

and this does not send anything to GA (even though the event handler is calling the ga(send...) method). How ever, if I use this exact technique for but with event.preventDefault(); at the beginning of the function, the event is sent and it appears in GA dashboard.

Is there some setting that I missed in order to make this work properly?

I am currently using analytics.js (the newer version of GA) and I am trying to track all types of events from my website, including when a user clicks on an anchor tag pointing to an external URL. I am currently using this setup:

 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics./analytics.js','ga');

  ga('create', 'UA-KEY-HERE', { 'alwaysSendReferrer': true, 'allowAnchor': true });

and I send the events when hitting a link like this:

$(document).on("click", ".anchor-class", function (event) {
    label = //get data from anchor element here ...  
    ga('send', 'event', 'Link Clicked', 'Click Details', label);;
    return;
    }
});

and this does not send anything to GA (even though the event handler is calling the ga(send...) method). How ever, if I use this exact technique for but with event.preventDefault(); at the beginning of the function, the event is sent and it appears in GA dashboard.

Is there some setting that I missed in order to make this work properly?

Share Improve this question asked Jan 23, 2014 at 9:50 Tamas IonutTamas Ionut 4,4105 gold badges38 silver badges62 bronze badges 3
  • Try a short timeout before your function returns, there might not be enough time to send the tracking request before the user is taken to the external url. – Eike Pierstorff Commented Jan 23, 2014 at 9:59
  • Added setTimeout(function () { }, 5050); before return, but did not changed anything. – Tamas Ionut Commented Jan 23, 2014 at 11:09
  • Using a timeout is a bad route to go, because you will either needlessly wait or you may not wait long enough. – CTS_AE Commented May 15, 2018 at 19:05
Add a ment  | 

3 Answers 3

Reset to default 2

Use the hitCallback function:

  $(document).on('click','a', function(event){
    event.preventDefault();
    var label = $(this).attr('href');

    ga('send', 'event', 'Link Clicked', 'Click Details', label, {
      'hitCallback': function(){
        window.location.href = label;
      }
    });
  });

As pointed out by Blexy, the correct way to do this is to use a hit callback. However, you also need to take into account that users may block Google Analytics using some privacy protection tool such as Ghostery, in which case the hit callback will never be executed. The following article explains how to implement this correctly:

http://veithen.github.io/2015/01/24/outbound-link-tracking.html

We currently had this issue and ported our analytics code off of the website and into GTM. Another issue is that we have hundreds of sites that cannot have the new code released to them to deprecate the on-page analytics, but we already had GTM on them.

We were able to find the jQuery events that were bound to the click event and write code in GTM that removes the jQuery event on those clicked buttons via the exact event handler. Then we were able to apply standard GTM click triggers and tags so we didn't get double eventing.

Assuming you can easily remove the code from the page the following should work great using GTM.

This will fire an event off to analytics when a user clicks a given element and it will make any navigation wait until the corresponding tags have finished firing first before letting the page navigate away.

GTM Implementation

This is the quick and standard way now with the newer GTM.

Pre-Setup

Variables

  • You will need access to the Click Element Built-In variable. You can enable this under Variables --> Configure --> Click Element.
  • Also enable the Page Path or Page URL Built-In variable. This is later used to help you determine which pages to run the trigger on.
  • It looks like you're trying to get some text off of the clicked element for the event. If so you should create a Custom JavaScript variable. This just gets the inner text of the element, but you could also get an attribute or whatever other data you're looking for at this step.
  • Name: Click Element - Inner Text
  • Variable Type: Custom JavaScript
  • Custom JavaScript: function() { return {{Click Element}}.innerText; }

Triggers

Create a new trigger

  • Trigger Type: Click - Just Links
  • Wait for Tags: Enable this, this is the magic you're looking for.
    • Max wait time: set this to what you feel is appropriate and if you can live with the possibility that you may loose some analytics for a better user experience. Imagine what the wait time may be for a 3G user on a mobile device. Is 5000ms enough, not enough, maybe 10000ms. The user probably understands their connection is bad.
  • Enable this trigger when all of these conditions are true:
    • NOTE: you should only run this on pages that you need to run it on. Google isn't very clear if there is a performance loss and their "Learn More" says nothing about it.
    • If you need this to run on all pages though, configure it like so:
      • Page Path matches RegEx .*
    • Otherwise you should write something like:
      • Page Path matches RegEx ^/path/my-page$ specific page
      • Page Path matches RegEx ^/path/my-page/.*
      • NOTE: I'm not sure if those regex are correct, I'm not sure if you'll get a path with a proceeding or appended forward slash / or if you need anchors - normally it's best to be explicit on anchors so you don't get any funny business.
  • This trigger fires on: Some Link Clicks
  • Fire this trigger when an Event occurs and all of these conditions are true. Choose one below that fits your needs and change it how you need it.
    • Click Element matches CSS selector a
    • or maybe something more specific?
    • Click Element matches CSS selector .container .calls-to-action a
    • maybe only on external links? Assuming all internal links are relevant pathing.
    • Click Element matches CSS selector a[href^="http"]

Tags

Create a new tag

  • Tag Type: Event
  • Category: Link Clicked
  • Action: Click Details
  • Label: {{Click Element - Inner Text}}
  • Google Analytics Settings: best to use these for reusability and consistency rather than manually setting them up.
  • Firing Triggers: The Link Clicking Trigger you created above.

本文标签: javascriptGoogle Analytics does not track link click eventsStack Overflow