I want to fetch cookie data from my Shiny app using shinyjs. I have created a cookie, "samplecookie=testval"; and I want to be able to retrieve the value of samplecookie. I use the below javascript function (where I pass the cookieName and it returns the corresponding value).
function fetchCookie(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";
Below is the javascript code in the shiny app
jsCode<-'shinyjs.tstfunc=
function (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";
}
}'
ui <- shinyUI(fluidPage(mainPanel(
useShinyjs(),
extendShinyjs(text = jsCode)
)))
server <- function(input, output)
{
observe({
x=js$tstfunc("samplecookie")
print(x)
})
}
shinyApp(ui=ui, server=server)
I am expecting that when I pass "samplecookie" as a parameter to the tstfunc() function, it should print "testval" on the console. But every time I keep getting a NULL value returned. Can someone help me understand what I am doing wrong? Appreciate any help. Thanks.
I'm the author of shinyjs. You cannot use it like that to pass values from JS to R. The only way to pass a value from JS to R is to use inputs. In JavaScript you'd have to call the Shiny.onInputChange()
function, and in R you need to add an observe/reactive statement that listens to that input being changed.
Read this page to learn about passing values from JS to R
The code you provide is a bit weird and hard to read so here's a simple example of how to do this. This code simply asks JavaScript to pass the current time to R, it's simple but it shows how to do this
library(shiny)
library(shinyjs)
jsCode <- 'shinyjs.gettime = function(params) {
var time = Date();
Shiny.onInputChange("jstime", time);
}'
ui <- fluidPage(
useShinyjs(),
extendShinyjs(text = jsCode, functions = "gettime")
)
server <- function(input, output) {
js$gettime()
observe({
cat(input$jstime)
})
}
shinyApp(ui = ui, server = server)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With