Stophface Stophface - 1 month ago 9
R Question

Receiving data from .js in server.R shiny

How would I receive data, created in a

.js
file in the
server.R
in shiny?

I am using the leaflat library and I need the extend the LatLngBounds of the current map view has. I need this variable in the
server.R
for furhter processing.

So i have

mycode.js

//get bounds of extend of view
$(document).ready(function() {

var myBounds = map.getBounds();
Shiny.onInputChange("bounds", myBounds);



});


which I include in the
ui.R
like

tags$body(tags$script(src="mycode.js"))


Thats how my
Server.R
looks like:

myBoundsR <- reactive(
as.numeric(input$bounds)
print(input$bounds)
)


However, how would I receive the data in the
server.R
file, coming from my
mycode.js
?

It feels like
Shiny.addCustomMessageHandler
is only to receive data in
.js
(or
.R
) while
session$sendCustomMessage
can only be used in the
.R
files? What would I use to send something from a
.js
file to the
server.R
file?!

Or can I simply use the variable
bound
as if I created it in the
server.R
file?!

Answer

Regarding what NicE wrote:

In the file.js

var myVariable = //do something
Shiny.onInputChange("variableNameToWriteInServer.R", myVariable)

In the server.R

observe({
# thats how you access the variable
    input$myVariable
#do something with the variable. To see if it worked something like
})

That should do the trick. If you use the getBounds() function keep that in mind Leaflet : Firing an event when bounds change. Also, you might not receive any output since the getBounds() function does not return the bounds of the window when the window extend is not changed. But, its only execute once. In the article I linked is a solution for this.

For further undocumented communication in Shiny (server.R and ui.R) read here: https://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/

Comments