首页 > 解决方案 > 退出闪亮的应用程序时添加“您确定要离开此页面”警报消息

问题描述

是否可以添加“您确定要离开此页面吗?” 当浏览器即将关闭时,向闪亮的应用程序退出消息?

不幸的是,我在 StackExchange 的其他地方找不到答案。我认为您可以使用 javascript 来执行此操作,尽管我对它不是很熟悉。提前非常感谢。

标签: rshiny

解决方案


实现这一点的最简单方法是window.onbeforeunload在 JavaScript 中使用。

另一个Stackoverflow 主题中接受的答案的代码:

window.onbeforeunload = function() {
  return 'Your changes will be lost!';
};

fluidPage您可以通过将其包含在Shiny 应用程序或dashboardBodyShiny 仪表板页面中来实现此(以及任何 JavaScript 代码) 。

JavaScript 代码需要包含在 head 和 script 标签中(与在 HTML 中包含 JS 文件时相同)

解决方案:

tags$head(tags$script(HTML("
    // Enable navigation prompt
    window.onbeforeunload = function() {
        return 'Your changes will be lost!';
    };
"))),

默认 Geyser 应用程序的可重现示例:

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)

推荐阅读