Search code examples
jqueryrgoogle-chromeshinyshinyjs

How to auto redirect to tab in shiny without blocked by chrome by auto clicking link in shiny?


I would like the shiny app to auto redirect to the url in a new tab. I tried to use window.open(), but the popup will be blocked by chrome

I also notice if the very first thing after clicking button is not to redirect the link, it will be blocked by chrome:

# it works
actionButton("download", "Download link", onclick ="window.open('https://www.stackoverflow.com');")

# but it will not work
ui <- fluidPage(useShinyjs(),  
                actionButton("download", "Download link"))

server <- function(input, output) {
  observeEvent(input$download, {
   
  # some functions to generate the link
  ##### Note: it will take ~20s #####
  url <- funs(...) 

  # but lets use SO for now
  url <- "https://www.stackoverflow.com"
  # auto direct to the link in a new tab
  runjs(paste0("window.open('", url, "', '_blank');"))
  })

}

shinyApp(ui, server)

I may think if there is any way to auto click the link tag below?

tags$a(href = "ww.google.com", "link to google", target = "_blank")

Edit:

I tried this way:

runjs(paste0(
      'let newTab = window.open();newTab.location.href = "https://www.stackoverflow.com";'
    ))

It somehow did not work in shiny: VM238:1 Uncaught TypeError: Cannot read properties of null (reading 'location').


Solution

  • It seems like no immediate solution to solve the issue if the auto redirection is not first thing after users click the button. It will be always blocked by chrome. Therefore, I give up auto redirection and have to add pop up box and ask users to click "ok" button.

    # something like below
    ui <- fluidPage(useShinyjs(),  
                    actionButton("download", "Download link"),
                    uiOutput("linktext"))
    
    server <- function(input, output) {
    
      observeEvent(input$download, {
       
      # some functions to generate the link
      ##### Note: it will take ~20s #####
      url <- funs(...) 
      output$linktext <- renderUI(tags$a(id="link-a", href = url, NULL, target = "_blank"))
    
      ## initiate fake popbox func to generate popup box
      popbox(inputId = "popup-box", "okay", "cancel")
    }
    
    observeEvent(input$popup-box, {
      req(input$popup-box == T)
      runjs("$('#link-a')[0].click();"))
    })