Track events in an R shiny app using Google Analytics

Jamie Lentin

There are various guides for keeping track of page views for Shiny, but as part of the FarFish project, we needed to measure not just who was using our R shiny apps, but how they were using it.

This can be achieved very easily by listening for Shiny's JavaScript events.

In the following we assume that we have a tabbed page called main_tabs:

tabsetPanel(type = "tabs", id = "main_tabs", ... )

...and an input widget called document_name:

selectInput("document_name", "Document name", list('a', 'b', 'c'), ''),

...and we would like to track whenever the user changes either.

Create the following as tracking.js, editing the top 2 lines as you see fit:

// Modify this with your own code, or leave as-is to debug
var ga_code = 'UA-XXXXX-Y'

// We only want to log changes of main_tabs or document_name
// you probably want different
var log_widgets = ['main_tabs', 'document_name'];

(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.com/analytics' + (ga_code === 'UA-XXXXX-Y' ? '_debug' : '')  + '.js', 'ga');

ga('create', ga_code, 'auto');

if (ga_code === 'UA-XXXXX-Y') {
    ga('set', 'sendHitTask', null);
}

$(document).on('shiny:connected', function(e) {
    ga('send', 'pageview');
});

$(document).on('shiny:inputchanged', function(e) {
    if (log_widgets.indexOf(e.name) > -1) {
        ga('send', 'event', 'widget', e.name, e.value);
    }
});

...then include this into your page by adding the following somewhere in ui.R:

tags$head(includeScript("tracking.js"))

That's it. If you have left the code as UA-XXXXX-Y then you should see any changes in the JavaScript console (press F12), if you used a real Google Analytics code then log in to see events coming through.