5

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

dpel
  • 1,954
  • 1
  • 21
  • 31
kay_arr
  • 53
  • 4

2 Answers2

12

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)
    })
  }
)
Pork Chop
  • 28,528
  • 5
  • 63
  • 77
0

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) })
  }
)
R.S.
  • 2,093
  • 14
  • 29