繁体   English   中英

R闪亮的询问确认,然后关闭应用/标签

[英]R shiny ask confirmation before closing app/tab

我想在标签/应用关闭之前显示确认模式,但前提是确实进行了更改。

我在这里找到了一些有用的功能但是每次我要关闭应用程序/选项卡时,它们都会显示模式。 在下面的示例中,我使用@Matee Gojra的goodbye功能。

我以为我可以将R中的布尔值发送到JavaScript,并且仅在进行更改的情况下执行该函数。

但是很明显,如果我在函数中包含if条件,它将不再起作用。

我该如何进行这项工作?

library(shiny)

js <- HTML("
var changes_done = false;

Shiny.addCustomMessageHandler('changes_done', function(bool_ch) {
  console.log('Are changes done?');
  console.log(bool_ch);
  changes_done = bool_ch;
});

function goodbye(e) {
  if (changes_done === true) {
    if(!e) e = window.event;

    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;

    //This is displayed on the dialog
    e.returnValue = 'Are you sure you want to leave without saving the changes?';

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
      e.stopPropagation();
      e.preventDefault();
    }
  }
}

window.onbeforeunload = goodbye;
")


ui <- fluidPage(
  tags$head(tags$script(js)),
  actionButton("add_sql", "Make Changes"),
  verbatimTextOutput("sqls")
)

server <- function(input, output, session) {

  sqlCmd <- reactiveVal(NULL)

  ## Simulate a Change
  observeEvent(input$add_sql, {
    sqlCmd(runif(1, 1, 1000))
  })

  output$sqls <- renderPrint({
    req(sqlCmd())
    sqlCmd()
  })

  ## Are changes made? Send to JS
  observe({
    if (!is.null(sqlCmd())) {
      session$sendCustomMessage("changes_done", 'true')
    } else {
      session$sendCustomMessage("changes_done", 'false')
    }
  })
}

shinyApp(ui, server)

如果此条件在JS代码段中的if (changes_done === true) {}被注释或删除,则该模式会在关闭应用程序之前显示,但不会。

您必须使用TRUE而不是'true'

session$sendCustomMessage("changes_done", TRUE)

FALSE ,不是'false'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM