如何通过在 shiny 中自动单击 link 来自动重定向到 shiny 选项卡而不被 chrome 阻止?

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

我希望闪亮的应用程序自动重定向到新标签页中的 url。我尝试使用 window.open(),但弹出窗口将被 chrome

阻止

我还注意到,如果点击按钮后的第一件事不是重定向 link,它将被 chrome:

# it works
actionButton("download", "Download link", onclick ="window.open('https://www.whosebug.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.whosebug.com"
  # auto direct to the link in a new tab
  runjs(paste0("window.open('", url, "', '_blank');"))
  })

}

shinyApp(ui, server)

我想有没有办法自动点击下面的link标签?

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

编辑:

我这样试过:

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

它在 shiny 中不知何故不起作用:VM238:1 Uncaught TypeError: Cannot read properties of null (reading 'location')

一个 hack 是创建一个 <a> 元素并模拟对此 link:

的点击
library(shiny)
library(shinyjs)

ui <- fluidPage(useShinyjs(), 
                tags$a(id = "visit-so", 
                       href = "https://www.whosebug.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.whosebug.com',
                                           target: '_blank'})[0].click();"))

}

shinyApp(ui, server)

因此,您要么在 DOM 中的某处永久创建 <a> 元素,要么创建一个临时 <a> 标签而不将其附加到 DOM。

如果用户单击按钮后自动重定向不是第一件事,似乎没有立即解决问题的方法。它将始终被 chrome 阻止。因此,我放弃了自动重定向,不得不添加弹出框并要求用户单击“确定”按钮。

# 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();"))
})