Find out when user leaves a page in django
I have an ajax function that sends requests to a Django view every second:
function get_updates() {
$.ajax({
url: full_path,
type: 'GET',
data: {latest_pk: latest_pk},
success: function(json) {
...
},
complete: function(data) {
setTimeout(get_updates, 1000);
}
});
}
get_updates();
get method of the view is like this:
def get(self, request, *args, **kwargs):
if request.GET:
# If there are GET parameters, use them to return updates.
response = self.get_updates(request.GET.get("latest_pk"))
return JsonResponse(response)
else:
# Otherwise if the url is simply requested,
# return the rendered chat page.
return super().get(request, *args, **kwargs)
How can I execute some code in Django, after requests stopped being sent? I need to save the time of the last request.
Try this in javascript there is event called ."beforeunload".
This is just an idea how you can achieve it
<script>
window.addEventListener("beforeunload",function(){
$.ajax({
url: full_path,
type: 'GET',
data: {latest_pk: latest_pk},
success: function(json) {
// add your other logic here
}
});
});
</script>