Logout User On Tab Close

Hi, there I’m trying to log a user out and update their online status in my table to false whenever they close the tab. I have the javascript event listener for when someone closes the tab but how would I call a python function from that event listener

Event Listener:

window.addEventListener('beforeunload', function (e) {
    var exited = True;
});

Code Sample:

#logout code to run on close
user=anvil.users.get_user(allow_remembered=True)
anvil.users.logout()
anvil.server.call('sign_out',user['email'])
open_form('Main')

#Server code
@anvil.server.callable
def sign_out(target):
  app_tables.users.get(email=target).update(online=False)

There’s a section in the docs that’s hard to find (it doesn’t come up when you search for Javascript) that talks about calling Python functions from Javascript: Anvil Docs | HTML Forms

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

Finally found my answer

@stucork What is the e that gets passed as a parameter in unload (I don’t see where it is used)?

I’m using a python function as a JavaScript callback for a JavaScript event listener.

When a JavaScript event fires and calls the callback it passes the event to the callback. So e is a JavaScript event. I don’t use it but I do need the argument otherwise python throws a TypeError for wrong number of arguments.

If I’m using python functions as callbacks in other libraries I might use *args if I don’t know how many args the JavaScript library will give me.

1 Like