Prevent user from leaving dash app

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:

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?"
1 Like