In many instances, you will want to send data from the R server to the JS client. Here is a very simple example:
library(shiny)
runApp(
list(
ui = fluidPage(
tags$script(
"Shiny.addCustomMessageHandler('message', function(params) { alert(params); });"
),
actionButton("btn","Press Me")
),
server = function(input, output, session) {
observeEvent(input$btn,{
randomNumber <- runif(1,0,100)
session$sendCustomMessage("message",list(paste0(randomNumber," is a random number!")))
})
}
)
)
The workhorses here are the session$sendCustomMessage
function in R
and the Shiny.addCustomMessageHandler
function in javascript
.
The session$sendCustomMessage
function lets you send parameters from R
to a javascript
function, and Shiny.addCustomMessageHandler
let's you define the javascript
function that accepts the parameters from R
.
Note: Lists are converted to JSON when they are passed from R
to javascript