Disconnect flask server when user closes browser

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.

  1. 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.
  2. The second JavaScript function sends a request to the Flask server if the user chooses to leave the page.
  3. 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)

Instead of writing javascript, you can listen for the page to close or reload by listening to the unloaded property of the component FefferyUnload ( https://fuc.feffery.tech/FefferyListenUnload )

hi @CNFeffery,

I don’t know why my dash app failed to run after I add a new component using FefferyUnload.
Thank you for the reply.

You can view the log information from the browser console and other places, we have not encountered problems in daily use, perhaps related to the low version of the browser compatibility.