Home > Enterprise >  Triggering a python function when tab closes with flask
Triggering a python function when tab closes with flask

Time:11-15

I'm trying to create a modern looking GUI so I decided to setup a simple flask app. Eventually, I want to pack the app up in a .exe file, so I want to start the server and open a web-browser when I start the flask app, and quit the server when I close the tab. My question is:

Is there any way to trigger a python function that quits the flask server when I close the tab?

Thank you for the help in advance!

CodePudding user response:

You can add an event listener to beforeunload event and send a request when the tab is about to close.

window.onbeforeunload = () => fetch('/stop');

When you confirm it, the request is sent, and you can shut down the server inside the handler.

The only downside is that the browser shows a popup, confirming if you really want to leave.

  • Related