The easiest way to achieve this is to use window.onbeforeunload
in JavaScript.
Code from the accepted answer in another Stackoverflow topic:
window.onbeforeunload = function() {
return 'Your changes will be lost!';
};
You can implement this (and any JavaScript code), by including it in fluidPage
for Shiny apps, or dashboardBody
for Shiny dashboard pages.
The JavaScript code needs to be wrapped in head and script tags (same as when you include a JS file in HTML)
Solution:
tags$head(tags$script(HTML("
// Enable navigation prompt
window.onbeforeunload = function() {
return 'Your changes will be lost!';
};
"))),
Reproducible example for the default Geyser app:
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Navigation prompt
tags$head(tags$script(HTML("
// Enable navigation prompt
window.onbeforeunload = function() {
return 'Your changes will be lost!';
};
"))),
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)