I want to know if it is possible to use variables created in runjs() in my R code.
For example will I be able to access the variable today_var outside the runjs() function for further analysis.
if (interactive()) {
library(shiny)
shinyApp(
ui = fluidPage(
useShinyjs(),
actionButton("btn", "Click me")
),
server = function(input, output) {
observeEvent(input$btn, {
runjs("var today_var = new Date(); alert(today);")
#print(today_var)
})
}
)
}
Thanks in advance
Theres wonderful function called Shiny.onInputChange it will do what you want
library(shiny)
library(shinyjs)
shinyApp(
ui = fluidPage(
useShinyjs(),
actionButton("btn", "Click me")
),
server = function(input, output) {
observeEvent(input$btn, {
runjs('var today_var = new Date(); alert(today_var);Shiny.onInputChange("today_var",today_var);')
})
observe({
print(input$today_var)
})
}
)
For some reason, the above code returned NULL for me.
However, following the process described in this article worked: Communicating with Shiny via JavaScript
This approach basically involves first setting a shiny input variable from within the javascript code, and then reading that input value reactively from within the shiny code.
library(shiny)
library(shinyjs)
shinyApp(
ui = fluidPage(
useShinyjs(),
actionButton("btn", "Click me")
),
server = function(input, output) {
observeEvent(input$btn, {
runjs('var today_var_js = new Date(); alert(today_var_js);
//Shiny.onInputChange("today_var",today_var);
//set shiny Input value to read reactively from R
Shiny.setInputValue("today_var_shiny", today_var_js);
')
})
#use the shiny Input value
#https://shiny.rstudio.com/articles/communicating-with-js.html
observeEvent(input$today_var_shiny, { print(input$today_var_shiny) })
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With