3

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.

  • 1
    Sounds like the [shinyalert](https://deanattali.com/blog/shinyalert-package/) package may be useful for this. – neilfws May 29 '19 at 23:43

2 Answers2

4

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)
GyD
  • 3,902
  • 2
  • 18
  • 28
0

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
    }

MAB
  • 43
  • 2
  • 7
  • Can you advise OP on how to include this JS code in their Shiny app through a reproducible example? – GyD May 30 '19 at 08:36
  • Thank you! Where would I put this code within the Shiny app code? As @GyD said, would be useful to see a reproducible example. Thanks again, appreciate your help. – user2243322 Jun 03 '19 at 23:34