Shiny open multiple browser tabs

给你一囗甜甜゛ 提交于 2021-02-07 07:26:24

问题


In my Shiny app I want to open several URL's with a short delay between opening. Here is some example code that works just fine when I run the app in my RStudio.

library(shiny)

URLs <- c("http://www.google.com", "http://www.stackoverflow.com")

ui <- fluidPage(
  actionButton(
    "click",
    "Click here to open several browser tabs"
  )
)

server <- function(input, output){
  observeEvent(input$click, {
    for (i in URLs){
      browseURL(i)
      Sys.sleep(1)                #Short delay of 1 second
    }
  })
}

shinyApp(ui, server)

However, when I run this app on shinyapps.io, browseURL() doesn't work (as mentioned here).

Does anyone know how to open multiple browser tabs with a short delay between opening them, so that it also works when the app is deployed on shinyapps.io? Would it be possible with R code or is JavaScript necessary?


回答1:


This is a pretty old question, but answering in case others stumble upon while searching.


As mentioned in the reference you linked, I think you need to use some JS to accomplish this task. Below is an example of using the shinyjs package to define a shiny compatible browseURL function. Once we have the function defined we add a few lines to the ui and then call it in the server as js$browseURL().

library(shiny)
library(shinyjs)

# define js function for opening urls in new tab/window
js_code <- "
shinyjs.browseURL = function(url) {
  window.open(url,'_blank');
}
"

URLs <- c("http://www.google.com", "http://www.stackoverflow.com")

ui <- fluidPage(
  # set up shiny js to be able to call our browseURL function
  useShinyjs(),
  extendShinyjs(text = js_code, functions = 'browseURL'),

  actionButton(
    "click",
    "Click here to open several browser tabs"
  )
)

server <- function(input, output){
  observeEvent(input$click, {
    for (i in URLs){
      js$browseURL(i)
      Sys.sleep(1)                #Short delay of 1 second
    }
  })
}

shinyApp(ui, server)


来源:https://stackoverflow.com/questions/41426016/shiny-open-multiple-browser-tabs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!