R Shiny 在关闭应用程序/选项卡之前询问确认。

3
我想在选项卡/应用关闭之前显示确认模态框,但仅当确实进行了更改时才显示。
我在这里找到了一些有用的函数(链接),但它们每次关闭应用程序/选项卡时都会显示模态框。在下面的示例中,我使用了@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) {}被注释或删除时,模态框会在关闭应用程序之前出现,但如果保留该条件则不会出现。"最初的回答"
1个回答

3

您需要使用 TRUE,而不是 'true'

session$sendCustomMessage("changes_done", TRUE)

而且,不是'false',而是FALSE


是的,那只是一个简单的修复!谢谢你! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接