问题描述
我想在选项卡/应用关闭之前显示确认模式,但前提是确实进行了更改.
I want to display a confirmation modal, before the tab/app closes but only if changes really have been made.
我在此处找到了一些有用的函数,但它们每次都显示模态我想关闭应用程序/标签.在下面的示例中,我使用@Matee Gojra的再见
函数.
I found some useful functions here but they show the modal every time I want to close the app/tab. In the example below I use the goodbye
-function from @Matee Gojra.
我以为我可以将R中的布尔值发送给JavaScript,并且仅在进行更改的情况下才执行该函数.
I thought I could send a boolean value from R to JavaScript and only execute the function in case a change has been made.
但是很明显,如果我在函数中包含if条件,它将不再起作用.
But apparently if I include an if-condition in the function it doesn't work anymore.
我该如何进行这项工作?或者这是故意做到的?
How can I make that work or is that not possible on purpose?
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)
当此条件 if(changes_done === true){}
在JS代码段中被注释掉或删除时,该模式会在关闭应用程序之前显示,但不会.
When this condition if (changes_done === true) {}
in the JS-snippet is commented out or deleted, the modal appears before closing the app, but with it it doesn't.
推荐答案
您必须使用 TRUE
,而不是'true'
:
session$sendCustomMessage("changes_done", TRUE)
和 FALSE
,而不是'false'
.
这篇关于R闪亮的询问确认,然后关闭应用程序/标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!