How can I get a button in Shiny to call both JavaScript and R code in parallel?

后端 未结 1 703
臣服心动
臣服心动 2021-02-15 11:39

I have an HTML button in Shiny that when clicked, calls the JavaScript function geocodeAddressStreet(...) in a .js file in the /www direct

相关标签:
1条回答
  • 2021-02-15 12:03

    So you want to have a button and when you click it, both a javascript function and some R code get called? I was able to do this with the onclick function from the shinyjs package (disclaimer: I wrote the package)

    library(shinyjs)
    
    jsCode <- "
    shinyjs.geocodeAddr = function(params) {
      alert('JavaScript called!');
      // geocodeAddressStreet(...)
    }
    "
    
    runApp(shinyApp(
      ui = fluidPage(
        useShinyjs(),
        extendShinyjs(text = jsCode),
        actionButton("btn", "Click me")
      ),
      server = function(input, output, session) {
        onclick("btn", {
          js$geocodeAddr()
          cat("R called as well")
        })
      }
    ))
    

    Basically, the onclick function is an R function that will run when the button is clicked. Within it you can obviously call R code easily, but you can also call JS code using the shinyjs package -- that's how I made a call to js$geocodeAddr. Look at the extendShinyjs function. Alternatively, instead of using extendShinyjs(), you can also use the usual approach of session$sendCustomMessage(...)

    0 讨论(0)
提交回复
热议问题