Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Javascript Variable in R Shiny Application

Tags:

r

shiny

shinyjs

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

like image 931
kay_arr Avatar asked Jul 20 '26 16:07

kay_arr


2 Answers

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)
    })
  }
)
like image 73
Pork Chop Avatar answered Jul 23 '26 06:07

Pork Chop


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) })
  }
)
like image 20
R.S. Avatar answered Jul 23 '26 06:07

R.S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!