我有一个Shiny App(实际上是一个交互式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);
这是一种基于屏幕尺寸检测(小)移动设备的方法。请注意,这故意排除了屏幕较大的平板电脑。
以下代码段检查屏幕大小是否低于768px,并使用onInputChange
作为名为is_mobile_device
的输入将结果发送到Shiny服务器。只有在页面加载并且Shiny UI完成加载时才会进行一次检查。
将它放在一个JS文件中并将其包含在您的UI中(例如,使用tags$script
在问题中完成):
$(document).on('shiny:sessioninitialized', function (e) {
var mobile = window.matchMedia("only screen and (max-width: 768px)").matches;
Shiny.onInputChange('is_mobile_device', mobile);
});
浏览器支持:http://caniuse.com/#feat=matchmedia
在你的Shiny server
函数中,你可以定义一个reactive
来检索值:
server <- function(input, output, session) {
is_mobile_device <- reactive(isTRUE(input$is_mobile_device))
# ...
}
有关在JavaScript端检测移动设备的其他方法(例如,基于用户代理也包括平板电脑),请在此处查看优秀答案: