Detect reload page or close browser button

Summary

Hi to everyone,
I’m developing a web app for my bachelor thesis with Streamlit, it’s a software that via bluetooth connects to BLE devices, each time a device is connected, the controller generates a thread that manages it. I am looking for a solution that will allow me to disconnect the devices (then call the “disconnect()” method) when the user clicks the page reload or browser close button. How can i do that?

Thanks in advace.