我有一个Shiny应用(实际上是一个交互式的R Markdown报告),我想根据用户是否在移动端来进行格式化。我找到了这篇由g3rv4撰写的博客文章,其中描述了如何测试这一点,但我无法在下面的示例应用程序中使其正常工作。
这里是
https://g3rv4.com/2017/08/shiny-detect-mobile-browsers
我是一名建模师,而非程序员,所以我可能在Javascript方面有些做错了。我没有收到任何错误信息,但是我没有从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)
这里是
www/js/mobile.js
文件: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);
flexdashboard
来满足简单的需求,特别是因为你说这是一个交互式的rmarkdown
报告。如果你需要更多的功能,可以看看shinydashboard
,但它有一个更陡峭的学习曲线。 - Kevin Arseneau