Reputation: 11192
in a shinty application, I'd like to redirect the user to another URL when she is clicking on a point in a plot. The redirect itself is working based on the solution presented in https://stackoverflow.com/a/47158654/590437, however, it's unclear to me how to incorporate a dynamic property(which is calculated on the server-side) into the URL.
Example:
library(shiny)
library(ggplot2)
jscode <- "Shiny.addCustomMessageHandler('mymessage', function(message) {window.location = 'http://www.google.com';});"
ui <- fluidPage(
tags$head(tags$script(jscode)),
plotOutput("scatter", click = "plot_click")
)
server <- function(input, output, session) {
observeEvent(input$plot_click, {
selectedTiles = nearPoints(iris, input$plot_click, threshold = 100, maxpoints = 1)
if(nrow(selectedTiles)>0){
# todo how to include the species in the redirect URL?
# e.g. https://www.google.com/?q=versicolor
session$sendCustomMessage("mymessage", "mymessage")
}
})
output$scatter = renderPlot({
ggplot(iris, aes(Sepal.Width, Petal.Width)) + geom_point()
})
}
shinyApp(ui,server)
So when triggering the redirect with sendCustomMessage
to run the java-script, how could I include a dynamic query parameter (in this example the selected species)?
Upvotes: 0
Views: 1408
Reputation: 29387
You just pass the argument into the mymessage
function, like so:
library(shiny)
library(ggplot2)
jscode <- "Shiny.addCustomMessageHandler('mymessage', function(message) { window.location = message;});"
ui <- fluidPage(
tags$head(tags$script(jscode)),
plotOutput("scatter", click = "plot_click")
)
server <- function(input, output, session) {
observeEvent(input$plot_click, {
selectedTiles = nearPoints(iris, input$plot_click, threshold = 100, maxpoints = 1)
if(nrow(selectedTiles)>0){
# todo how to include the species in the redirect URL?
url <- "https://stackoverflow.com/questions/57755830/how-to-redirect-to-a-dynamic-url-in-shiny/57756048#57756048"
session$sendCustomMessage("mymessage", url)
}
})
output$scatter = renderPlot({
ggplot(iris, aes(Sepal.Width, Petal.Width)) + geom_point()
})
}
shinyApp(ui,server)
Upvotes: 2