【问题标题】:How to redirect to a dynamic URL in shiny?如何重定向到闪亮的动态URL?
【发布时间】:2019-09-02 11:03:37
【问题描述】:

在一个 shinty 应用程序中,当用户单击绘图中的某个点时,我想将用户重定向到另一个 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 脚本时,我如何包含动态查询参数(在本例中为所选物种)?

【问题讨论】:

    标签: javascript r shiny


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多