Triggering session$onSessionEnded using Javascript

I have a shiny app running in the Electron framework (not a browser), and I'd like to quit R and stop shiny when I close the Electron app.

Usually, you can just add something like this to server.R:

session$onSessionEnded(function() {

If I can figure out how to trigger the custom callback from Electron, I imagine this code will still work. However, it only works in a browser :(.

HI @Dripdrop12,

I can think of two approaches.

I believe the direct way you're looking for is to send an event back to Shiny and then run your shutdown code. describes an example in the "From Javascript to R" section.

Another way would be to hide a shiny button and programmatically "click" the button when you close your app. An observe({myButton(); shutdown() }) could be executed when the button value changes. This is a round-about way to solve it, but uses native shiny hooks.


1 Like

Thanks! I read that guide. Is the correct Javascript method shiny.onSessionEnded? I looked through the shiny.js code on Github and could not find it listed explicitly and it is not discussed in the article.

I imagine because it is registered as a callback function when the shiny app starts it won't be listed in the source code.

I would try to use Shiny.setInputValue("myInput", "myValue") in javascript and use input$myInput() inside and observe() in R.

// when you have detected that the user wants to leave
on("app_close", function() {
  Shiny.setInputValue("myInput", "closeApp")
server <- function(input, output) {
  # ....
    if (identical(input$myInput, "closeApp")) {