StuartM
StuartM

Reputation: 6813

Tracking Social Tweets on Website with Google Analytics

We have a website which holds a Twitter Tweet button. We are looking to track the social events for clicking on the tweet button.

We are using the newer Universal Analytics and following this example: https://developers.google.com/analytics/devguides/collection/analyticsjs/social-interactions

For twitter we include their JS as follows:

<script async defer>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
</script>

We are having issues binding to the tweet event as described on Twitter here: https://dev.twitter.com/web/javascript/events

The issue is that 'twttr is not defined'. There is a similar question on SO here: ReferenceError: "twttr is not defined" even while using twttr.ready()

I have tried to implement the same approach here, but I am not getting any of the console logs appear?

<script>
window.addEventListener("load", function() {
    document.getElementById('twitter-wjs').addEventListener('load', function() {
      console.log('1');
        twttr.ready(function (twttr) {
          console.log('2');
            twttr.events.bind('tweet', function(e){
              console.log('3');
                if(!e) return;
                ga('send', 'social', 'twitter', 'tweet', theURL);
                console.log('tweet');
            })
        });
    }, false);
}, false);
</script>

How can we track the Twitter Tweet clicks in GA?

Upvotes: 1

Views: 101

Answers (1)

Philip Walton
Philip Walton

Reputation: 30431

The problem is you're adding a load event handler for the Twitter widget script inside the window object's load event callback. If the Twitter widget's script code is part of the page's initial content, then the browser will download that script and run it before firing the window's load event.

In other words, you script's load handler is never running because its load event has already happened -- before you added the listener for it.

You can update your code to check if the twttr object is there prior to adding the load listener for the script:

window.addEventListener("load", function() {

  function onTwttrReady() {
    twttr.events.bind('tweet', function(e){
      if(!e) return;
      ga('send', 'social', 'twitter', 'tweet', theURL);
      console.log('tweet');
    })
  }

  if (window.twttr) {
    onTwttrReady();
  } else {
    document.getElementById('twitter-wjs')
            .addEventListener('load', onTwttrReady);
  }
});

Upvotes: 2

Related Questions