Skip to content

Instantly share code, notes, and snippets.

@hypebright
Created February 13, 2022 09:36
Show Gist options
  • Save hypebright/db80d26ad21c936d9877697de7fedda2 to your computer and use it in GitHub Desktop.
Save hypebright/db80d26ad21c936d9877697de7fedda2 to your computer and use it in GitHub Desktop.
library(shiny)
ui <- fluidPage(
shinyjs::useShinyjs(),
# event handler in JavaScript: handles requests from R
# tells JavaScript to call the function and to pass it a message that it got from R
tags$head(
tags$script("
Shiny.addCustomMessageHandler('fetch-localstorage-item', function(message) {
const myitem = localStorage.getItem(message.key)
Shiny.onInputChange(message.input, myitem)
});
"),
textInput(inputId = 'textinput_key',
label = 'Key'),
textInput(inputId = 'textinput_value',
label = 'Value'),
actionButton(inputId = 'store_item',
label = 'Go!')
)
)
server <- function(input, output, session) {
observeEvent(input$store_item, {
# Set item in local storage
shinyjs::runjs(glue::glue("localStorage.setItem('{key}', '{value}')",
key = input$textinput_key,
value = input$textinput_value))
# calling JavaScript function from Shiny (as defined in UI scripts) to send information to Shiny
session$sendCustomMessage(type = "fetch-localstorage-item", message = list(key = input$textinput_key, input = "mylocalstore"))
})
# When Shiny receives updated information, print something
observeEvent(input$mylocalstore, {
print(paste0('I received the item with value ', input$mylocalstore))
})
}
shinyApp(ui, server)
@hypebright
Copy link
Author

If you try it out with key = test and value = 1, you’ll see this when you check the local storage in your browser (Safari example):
localstorage1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment