如何重定向到闪亮的动态URL?

时间:2019-09-02 11:03:37

标签: javascript r shiny

在简洁的应用程序中,当用户单击绘图中的某个点时,我想将其重定向到另一个URL。重定向本身基于https://stackoverflow.com/a/47158654/590437中介绍的解决方案进行工作,但是,我不清楚如何将动态属性(在服务器端计算)合并到URL中。

示例:

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)

因此,当使用sendCustomMessage触发重定向以运行Java脚本时,如何添加动态查询参数(在此示例中为选定的种类)?

1 个答案:

答案 0 :(得分:1)

您只需将参数传递给mymessage函数,就像这样:

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)