I’m developing a Dash app and would like my app to disconnect from the Flask server when the user closes the browser.
My implementation involves two JavaScript functions and setting up the Flask server connection.
- The first JavaScript function pops up a window to confirm whether the user wants to stay on the current page or leave when closing the browser.
- The second JavaScript function sends a request to the Flask server if the user chooses to leave the page.
- If the Dash app receives a “disconnect” signal, it can terminate the current job to disconnect from the Flask server.
However, I noticed that this method works when the user closes the browser but also gets mistakenly triggered when the server automatically fetches static resources such as assets. When I run my app for a while, it seems the Flask server automatically reloads assets and other Dash components. This server behavior also triggers my second JavaScript function, causing my app to close unexpectedly.
Does anyone have any suggestions for this issue?
// custom-script.js
window.addEventListener('beforeunload', function (event) {
var message = 'Are you sure you want to leave page?';
event.returnValue = message;
return message;
});
window.addEventListener('unload', function () {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/disconnect', false);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send(JSON.stringify({ message: 'User is leaving the page' }));
});
#Dash APP
from dash import Dash, html
from flask import request
import os, signal
app = Dash(__name__)
server = app.server
app.layout = html.Div([
html.H1("Dash App"),
#...
html.P("This is a Dash application.")
])
# Set Flask server connection
@server.route('/disconnect', methods=['POST'])
def disconnect():
data = request.get_json()
if data=={ 'message': 'User is leaving the page' }:
os.kill(os.getpid(), signal.SIGTERM)
return 'disconnected'
else:
return 'stay'
if __name__ == '__main__':
app.run_server(debug=True)