Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
fugu Avatar asked May 26 '18 10:05

fugu


People also ask

Can you embed a Shiny app on website?

Yes! A shiny app can be put in an iframe in another website from RStudio Connect. In order to put the app in an iframe, it is recommended to add a content URL, because you can move it to another piece of content should the need arise.

Is Shiny app secure?

shinyapps.io is secure-by-design. Each Shiny application runs in its own protected environment and access is always SSL encrypted.


1 Answers

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"))), ...

like image 76
S-K Avatar answered Oct 15 '22 17:10

S-K