12

I am building a Shiny application, where I want to stop the (local) server when the client is closed. A simple way to achieve this is to include this in the shinyServer function:

session$onSessionEnded(function() {
    stopApp()
})

A downside to this approach is if the user decides to hit refresh, then the app dies.

I have tried various workarounds, using e.g. reactiveTimer/invalidateLater to check for connections at certain intervals. However, these take a session reference (they are specific to the session), and so nothing will execute after onSessionEnded.

Is there a way to have a "global" server timer that executes regularly, and coould check for active connections? Or another way to achieve automatic application shut-down but which allows for a refresh of the page?

Stefan
  • 1,835
  • 13
  • 20

1 Answers1

4

You could add an actionButton and some code on the server to stop the app when the button is clicked. For example:

runApp(list(
  ui = bootstrapPage(
    actionButton('close', "Close app")
  ),
  server = function(input, output) {
    observe({
      if (input$close > 0) stopApp()
    })
  }
))

However, this won't automatically close the browser window (unless you're viewing with RStudio's built-in browser window). To do that, you need to add some Javascript to the actionButton.

runApp(list(
  ui = bootstrapPage(
    tags$button(
      id = 'close',
      type = "button",
      class = "btn action-button",
      onclick = "setTimeout(function(){window.close();},500);",
      "Close window"
    )
  ),
  server = function(input, output) {
    observe({
      if (input$close > 0) stopApp()
    })
  }
))

Of course, this won't stop the app when the user closes the window some other way. I believe it's also possible to detect window close events in the browser, and then you may be able to set an input value (which goes to the server) at that time, but I don't know whether it'll get to the server before the window is closed and the Javascript stops running.

data_steve
  • 1,548
  • 12
  • 17
wch
  • 4,069
  • 2
  • 28
  • 36
  • Yeah, I did consider this solution; but the primary reason for having this is that (some) users have a habit of refreshing pages and closing windows using the close button. It's hard to deal with both. So it is not meant as as feature, more as a "guard"... The server is run as a small local (portable) R, which is hidden from the user. The client is a portable chrome. When this closes, the server should stop itself and quit nicely. But not if the user refreshes the "page". – Stefan Jul 09 '14 at 13:51
  • when I run first code chunk in R console, it stops app. When I run this second code chunk, I get it to close browser tab; but it doesn't stop app. Suggestions? – data_steve May 26 '16 at 18:47