是否可以添加“您确定要离开此页面吗?”当浏览器即将关闭时,退出消息到Shiny App?
很不幸,我在StackExchange的其他地方找不到答案。我认为您可以使用javascript来做到这一点,尽管我对此并不十分熟悉。提前非常感谢。
答案 0 :(得分:1)
最简单的方法是在JavaScript中使用window.onbeforeunload
。
另一个Stackoverflow topic中接受的答案中的代码:
window.onbeforeunload = function() {
return 'Your changes will be lost!';
};
您可以通过将其包含在fluidPage
(对于Shiny应用程序)或dashboardBody
(对于Shiny仪表板页面)中来实现此代码(以及所有JavaScript代码)。
JavaScript代码需要包装在head和script标签中(与在HTML中包含JS文件时相同)
tags$head(tags$script(HTML("
// Enable navigation prompt
window.onbeforeunload = function() {
return 'Your changes will be lost!';
};
"))),
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)
答案 1 :(得分:0)
使用一些Jquery / JS,您可以完成此操作:
我在以下位置发现了以下东西:
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
}