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')
.
CodePudding user response:
A hack would be to create a <a>
element and simulate a click on this link:
library(shiny)
library(shinyjs)
ui <- fluidPage(useShinyjs(),
tags$a(id = "visit-so",
href = "https://www.stackoverflow.com",
"SO",
target = "_blank"),
actionButton("go", "Visit SO"),
actionButton("go2", "Visit SO"))
server <- function(input, output) {
observeEvent(input$go, runjs("$('#visit-so')[0].click();"))
observeEvent(input$go2, runjs("$('<a>', {href: 'https://www.stackoverflow.com',
target: '_blank'})[0].click();"))
}
shinyApp(ui, server)
So either you create the <a>
element somewhere in your DOM for good, or you create a temporary <a>
tag without appending it to the DOM.
CodePudding user response:
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();"))
})