fugu
fugu

Reputation: 6578

Embed Google analytics tracking code in shiny app

I have been using Google analytics to track activity on a shiny web app using the following at the top of my ui.R:

shinyUI(fluidPage(
    tags$head(HTML(
        "<script>
        (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.js','ga');

        ga('create', 'XXXXXXX', 'auto');
        ga('send', 'pageview');

        </script>"
      )),
...
)

However, I recently registered a new app and the tracking code I get from Google analytics is:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'XXXXX');
</script>

Following RStudio's instructions I have saved this as google-analytics.js and inplace of tags$head(HTML("...")) I have:

includeScript("google-analytics.js")

However this does not work. The instructions from the above link say:

Warning: the includeScript function places the content of the script inside a pair of script tags . If you copy and paste Javascript code into a .js file be sure to remove these tags

I have experimented with removing <script> and </script>, as well as the html tags surrounding async src="https://www.googletagmanager.com/gtag/js?id=XXXXX" but neither work.

Can anyone shed some light on how to get this working properly?

Upvotes: 12

Views: 2355

Answers (1)

S-K
S-K

Reputation: 79

Based on this article by Douglas Watson, all you have to do is:

  1. Copy the analytics HTML snippet into a text file. (created a file named google_analytics.R, in the same directory as ui.R)
  2. Include it in ui.R

    shinyUI(fluidPage( tags$head(includeHTML(("google-analytics.html"))), ...

Upvotes: 2

Related Questions