Created
February 13, 2022 09:36
-
-
Save hypebright/db80d26ad21c936d9877697de7fedda2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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):