Logout User On Tab Close

Why not move the definition to python then you can just create a python function as the handler for the javascript beforeunload event.

You’d probably want to define this above your startup form or within a startup module.

# Client side
import anvil.server
from anvil.js import window

def unload(e):
  print('unloading from client')
  anvil.server.call('server_unload')
  
window.addEventListener('beforeunload', unload)
# Server side
@anvil.server.callable
def server_unload():
  print('unloading from server')
  # do some server side stuff

When testing the behaviour make sure you interact with the page otherwise some browsers won’t fire the beforeunload event.

2 Likes