Skip to content

Instantly share code, notes, and snippets.

@jcrodriguez1989
Last active December 2, 2024 14:56
Show Gist options
  • Save jcrodriguez1989/a6a9c4168262e99ef2f9c70a110886ab to your computer and use it in GitHub Desktop.
Save jcrodriguez1989/a6a9c4168262e99ef2f9c70a110886ab to your computer and use it in GitHub Desktop.
Google Analytics Setup for Shiny
if (!requireNamespace("shiny")) stop("Please install the Shiny R package.")
# box::use(
# shiny[HTML, tags]
# )
#' Configure Google Analytics
#' This function must be called from a Shiny app's UI.
#' You can call use_google_analytics() from anywhere inside the UI, as long as the final app UI
#' (HTML code) contains the result of use_google_analytics().
#' @param ga_id The Google Analytics Tag ID, something like "G-ABCD12E34F".
use_google_analytics <- function(ga_id) {
shiny::tags$head(shiny::HTML(paste0(
"<!-- Google tag (gtag.js) -->\n",
'<script async src="https://www.googletagmanager.com/gtag/js?id=', ga_id, '"></script>\n',
"<script>\n",
" window.dataLayer = window.dataLayer || [];\n",
" function gtag(){dataLayer.push(arguments);}\n",
" gtag('js', new Date());\n",
" gtag('config', '", ga_id, "');\n",
"</script>\n"
)))
}
# library("shiny")
#
# ui <- fluidPage(
# use_google_analytics("G-ABCD12E34F"),
# h1("Congratulations! Google Analytics is tracking this visit!")
# )
#
# server <- function(input, output, session) {
#
# }
#
# shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment