State management with jQuery access

Viewed 45

How can a user defined app state be stored using R Shiny so that it is both accessible in R code and in jQuery code?

For example, my app has two states black and white. Options for storing the current state include

  • as hidden text in the DOM
  • as a data attribute of an DOM element
  • use local storage on the browser

Is there a better approach that is built in to Shiny for this purpose? Something like having a global variable defined in R that can be read in jQuery without having to send a message.

1 Answers

The canonical approach to communicate with JavaScript is indeed via sending a message.

Of course you can rely on pure HTML <-> JS communication means as well:

library(shiny)

read_js <- "$(function() {
  $('#output').append(`Text from data: ${$('#constant_data').data('state')}`, 
                      $('<br>'),
                      `Text from hidden: ${$('#constant_hidden').text()}`,
                      $('<br>'),
                      `Text from session: ${sessionStorage.getItem('constant_session')}`,
                      $('<br>'),
                      `Text from window: ${window.state}`);
});
"


ui <- fluidPage(
   tags$head(tags$script("sessionStorage.setItem('constant_session', 'black');
                          window.state = 'black';")),
   tags$head(tags$script(HTML(read_js))),
   div(id = "constant_data", `data-state` = "black"),
   div(id = "constant_hidden", "black", style = "display: none"),
   div(id = "output"),
)

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

shinyApp(ui, server)

And the choice of the method is up to you.

Some questions which may guide your choice:

  1. Should the state by visible in the DOM?
  2. Does the state change over time?
  3. Should the state be persistent over sessions?
Related