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?
A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes. If you want to set a timeout interval that is shorter or longer than the default, use the Timeout property. Note: The main problem with sessions is WHEN they should end.
Session timeout represents the event occuring when a user does not perform any action on a web site during an interval (defined by a web server). The event, on the server side, changes the status of the user session to 'invalid' (ie.
OWASP recommends application builders to implement short idle time outs (2-5 minutes) for applications that handle high-risk data, like financial information. It considers that longer idle time outs (15-30 minutes) are acceptable for low-risk applications.
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.
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