user2243322
user2243322

Reputation: 33

Adding a "are you sure you want to leave this page" alert message when exiting a shiny app

Is it possible to add a "Are you sure you want to leave this page?" exit message to a Shiny App when the browser is about to be closed?

I unfortunately can't find the answer elsewhere on StackExchange. I'm thinking that you can possibly do this using javascript, though I'm not super familiar with it. Thanks so much in advance.

Upvotes: 3

Views: 2223

Answers (2)

GyD
GyD

Reputation: 4072

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)

Upvotes: 4

MAB
MAB

Reputation: 43

With some Jquery/ JS you could accomplish this:

I found the following at:

https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

    var validNavigation = false;
    function wireUpWindowUnloadEvents() {
     /*
     * List of events which are triggered onbeforeunload on IE
     * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
     */

     // Attach the event keypress to exclude the F5 refresh
     $(document).on('keypress', function(e) {
       if (e.keyCode == 116){
         validNavigation = true;
       }
     });

     // Attach the event click for all links in the page
     $(document).on("click", "a" , function() {
       validNavigation = true;
     });

     // Attach the event submit for all forms in the page
     $(document).on("submit", "form" , function() {
       validNavigation = true;
     });

     // Attach the event click for all inputs in the page
     $(document).bind("click", "input[type=submit]" , function() {
       validNavigation = true;
     });

     $(document).bind("click", "button[type=submit]" , function() {
       validNavigation = true;
     });

    }



    function windowCloseEvent()
           {
            window.onbeforeunload = function() {
             if (!validNavigation){
              callServerForBrowserCloseEvent();
             }
            }
           }



    function callServerForBrowserCloseEvent()
    {
     alert("Are you sure you want to close this window?");
    // Or you could call a bootstrap modal here and give it yes/no buttons
    }

Upvotes: 0

Related Questions