I have a Shiny App (actually an interactive R Markdown report) that that I want to format depending on whether the user is on mobile or not. I found this blog post by g3rv4 which describes how to test for this, but I haven't been able to get it to work in the example app below.
https://g3rv4.com/2017/08/shiny-detect-mobile-browsers
I am a modeller, not a programmer, so there's probably something about the Javascript that I am doing wrong. I am not getting an error, but I am not getting any output from textOutput('isItMobile')
.
# shiny example from
# https://shiny.rstudio.com/tutorial/written-tutorial/lesson1/
# mobile detect code from
# https://g3rv4.com/2017/08/shiny-detect-mobile-browsers
library(shiny)
onStart <- function(input, output) {
### function to detect mobile ####
mobileDetect <- function(inputId, value = 0) {
tagList(
singleton(tags$head(tags$script(src = "js/mobile.js"))),
tags$input(id = inputId,
class = "mobile-element",
type = "hidden")
)
}
}
# Define UI for app that draws a histogram ----
ui <- fluidPage(
# App title ----
titlePanel("Hello Shiny!"),
mobileDetect('isMobile'),
textOutput('isItMobile'),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot")
)
)
)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
output$isItMobile <- renderText({
ifelse(input$isMobile, "You are on a mobile device", "You are not on a mobile device")
})
# Histogram of the Old Faithful Geyser Data ----
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#75AADB", border = "white",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
}
# this is how you run it
print('Running Simple Shiny App - Hit ESC to quit.')
shinyApp(ui = ui, server = server, onStart = onStart)
Here is the www/js/mobile.js
file:
var isMobileBinding = new Shiny.InputBinding();
$.extend(isMobileBinding, {
find: function(scope) {
return $(scope).find(".mobile-element");
callback();
},
getValue: function(el) {
return /((iPhone)|(iPod)|(iPad)|(Android)|(BlackBerry))/.test(navigator.userAgent)
},
setValue: function(el, value) {
},
subscribe: function(el, callback) {
},
unsubscribe: function(el) {
}
});
Shiny.inputBindings.register(isMobileBinding);