How to Access Browser Session/Cookies from Within Shiny App

Read in cookie to Shiny application with embedded javascript

Shinyjsis probably the way tog go with this.

Here's how you can read in a cookie without using shinyjs:

# UI file of getCookie Shiny application.
ui <- shinyUI(fluidPage(
titlePanel('Cookie'),
tags$head(tags$script(
HTML('
Shiny.addCustomMessageHandler ("readCookie",function (message) {
var cookie = readCookie(message.name);
Shiny.onInputChange("cookie", cookie);
})

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==" ") c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return "No such cookie";
}
')
)),
sidebarPanel(
actionButton('readCookie','Get Cookie'),
textInput('cookieName','Name of cookie: ')
),
mainPanel(
textOutput('cookieVal')
)
))

# Server file of getCookie Shiny application.
server <- shinyServer(function(input, output,session){
observeEvent(input$readCookie,{
session$sendCustomMessage(type="readCookie",
message=list(name=input$cookieName))
})

observeEvent(input$cookie,{
output$cookieVal <- renderPrint({ input$cookie })
})
})

shinyApp(ui=ui, server=server)

Run

document.cookie="username=John Doe";

In your browser console to create a cookie.

Shiny app session cookie is not found the first time

The observe function is triggered firstly when the input variable jscookie is created by your shiny application. In this case jscookie is still NULL. Adding the js$getcookie() before printing input$jscookie doesn't change that because the assignment happens at the end of your observer.

The second trigger happens after you applied the function js$getcookie(). In this case a cookie is found.

You can avoid the double trigger by using an observeEvent(...) function and adding the getcookie() function outside the observer. Now the function is executed before the observer is executed.

js$getcookie()
observeEvent(input$jscookie, {
print("Checking for cookie")
print(input$jscookie)
if (!is.null(input$jscookie) && input$jscookie != "") {
print("Cookie found")
user(input$jscookie)
} else {
print("No cookie found")
user(NULL)
}
})

how should I access shiny user's session info?

Per the shiny scoping rules, everything inside server <- function(input, output, session) is per-session.

server <- function(input, output, session) {
# everything in here is run once per-session, so it should run as soon as
# a user starts using the app
started <- Sys.time()
# ... reactives here ...
session$onSessionEnded(function() {
UserInfo <- data.frame(
LoginName = session$user,
Time = as.character(Sys.time())
)
# ... do something with UserInfo ...
})

In fact, the scoping rules suggest exactly this, but they named it startTime instead. (Hard things: cache invalidation and variable naming.)



Related Topics



Leave a reply



Submit