Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiny open multiple browser tabs

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?

like image 927
Teun Avatar asked Jan 02 '17 11:01

Teun


1 Answers

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().

Note that a pop-up blocker might block the effects of opening multiple tabs. Check your blocker settings if things don't seem to work.

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)
like image 153
Adam Spannbauer Avatar answered Oct 01 '22 06:10

Adam Spannbauer