Search code examples
shinyshinydashboardshinyjs

Reload a page and switch to tab


I use the package shinyjs to allow the user to reload the page by clicking on "Reload the page" button in Tab 2 and I would like to stay on Tab 2 after reloading the page. But after realoading, the page is taking to Tab1 instead of Tab2

How can we fix it ? This is my code below :

library(shiny)
library(shinyjs)

jscode <- "shinyjs.refresh = function() { history.go(0); }"

ui <- fluidPage(
  
  useShinyjs(),
  
  extendShinyjs(text = jscode, functions = "refresh"),
  
  tabsetPanel(
    tabPanel("Tab 1"),
    tabPanel("Tab 2", actionButton("mybutton", "Reload the page", 
                                   onclick ="javascript:window.location.reload(true)")))
  
)

server <- function(input, output, session) {
  
  
}

shinyApp(ui = ui, server = server)

Some help would be appreciated


Solution

  • You can resort to plain JavaScript. The idea is that you provide an id to tabsetPanel such that you can use updateTabsetPanel in the server.

    All you have to do then is to let the reloaded page know that you want to start on the second tab. As a refresh typically resets all of the inputs and reactives (you are aware of that, right?), you cannot use reactives and you have to rely on another way of communication. The query string would be one possibility.

    With these ingredients you can:

    1. Write a simple JavaScript function that reloads the page and adds a parameter to the url.
    2. Parse the query string in the server and if the parameter is found, react on it accordingly.
    library(shiny)
    
    js <- HTML("
               function doReload(tab_index) {
                  let loc = window.location;
                  let params = new URLSearchParams(loc.search);
                  params.set('tab_index', tab_index);
                  loc.replace(loc.origin + loc.pathname + '?' + params.toString());
               }")
    
    ui <- fluidPage(
       tags$head(tags$script(js, type ="text/javascript")),
       tabsetPanel(
          tabPanel("Tab 1", value = "tab1"),
          tabPanel("Tab 2", value = "tab2", 
                   actionButton("mybutton", "Reload the page", 
                                onclick = "doReload('tab2')")),
          id = "tabsets"
          
       )
    )
    
    
    server <- function(input, output, session) {
       observe({
          params <- parseQueryString(session$clientData$url_search)
          if ("tab_index" %in% names(params)) {
             updateTabsetPanel(session, "tabsets", selected = params$tab_index)   
          }
       })
    }
    
    
    shinyApp(ui = ui, server = server)