Is there a way to prevent a user from leaving the dash app e.g. when closing the browser or changing the URL. The use-case is if there is unsaved data that needs to be written to database. I’m thinking of showing a dialog that asks if the user really wants to leave and that data will be lost if he does so.
A way to deal with this is by using JavaScript. JavaScript can be included in a Dash app via the assets directory:
https://dash.plotly.com/external-resources
Then one can use straight forward JavaScript code to let the user confirm the exit of the page:
// This default onbeforeunload event
window.onbeforeunload = function(){
return "Do you want to leave?"
}
2 Likes
Due to security reasons, modern browsers do not allow custom messages in the onbeforeunload event. Instead, they display a generic message to prevent abuse. This behavior cannot be overridden.