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() {
  stopApp()
  q("no")
})

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. https://shiny.rstudio.com/articles/communicating-with-js.html 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.

Best,
Barret

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.

javascript
// when you have detected that the user wants to leave
on("app_close", function() {
  Shiny.setInputValue("myInput", "closeApp")
});
R
server <- function(input, output) {
  # ....
  observe({
    if (identical(input$myInput, "closeApp")) {
      stopApp()
      q("no")
    }
  })
}
2 Likes