Reputation: 213
I am trying to track user interactions in R Shiny using Google Analytics. I have been referring to the following guides: https://shiny.rstudio.com/articles/google-analytics.html https://shiny.rstudio.com/articles/usage-metrics.html
I have the following Java script saved as google-analytics.html
:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-1');
$(document).on('shiny:inputchanged', function(event) {
if (event.name === 'hub') {
ga('send','event', 'input',
'updates', event.name, event.value);
}
});
$(document).on('shiny:inputchanged', function(event) {
if(event.name === 'hub'){
alert('Changed Hub');
}
});
$(document).on('shiny:connected', function(event) {
alert('Connected to the server');
});
</script>
Right now this is tracking people that are in the app, but it is not sending the event information when they change information in the hub
input. I added the two alerts at the end of the script to make sure I am identifying the correct object and, sure enough, when the user changes the hub
input, they get an alert.
The short version of the ui
is as follows:
ui <-
fluidPage(
tags$head(includeHTML(("google-analytics.html"))),
# Sidebar
sidebarLayout(
sidebarPanel(
radioButtons("hub", label = h3("Hub"),
choices = list("Location 1", "Location 2",
"Both"),
selected = "Location 1"))),
# Main Panel
mainPanel(verbatimTextOutput("test"))
)
The server
is not relevant, but if needed, a play example is as follows:
server <- function(input, output) {
output$test<-renderPrint({input$hub})
}
Can anyone help me out? Why isn't the event being sent to Google Analytics?
Upvotes: 3
Views: 529
Reputation: 14189
You are mixing gtag.js
code and analytics.js
code.
You are using gtag
as library so you have to send an event with this code:
gtag('event', <action>, {
'event_category': <category>,
'event_label': <label>,
'value': <value>
});
https://developers.google.com/analytics/devguides/collection/gtagjs/events
In your case use this:
gtag('event', 'updates', {
'event_category': 'input',
'event_label': event.name,
'value': event.value
});
instead of this:
ga('send','event', 'input',
'updates', event.name, event.value);
}
Upvotes: 2