简体   繁体   中英

How to detect when a user Close browser/tab in flask back-end not in front-end (if not valid javascript)

As I'm using the session to close after 10min the user is inactive. But now I want to clear the Session when a user closes the browser or tab.

from flask import Flask, render_template, request, session, redirect, url_for, flash, Response, Blueprint, jsonify, \
    send_file,copy_current_request_context
import string
import random
import base64
import binascii
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os

app = Flask(__name__,template_folder='templates',static_folder='static')
secret_key_=os.urandom(24)
app.secret_key = secret_key_
app.config['SESSION_TYPE'] = 'filesystem'
app.debug = True
BLOCK_SIZE = 16



def pad(data):
    length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
    return data + chr(length)*length

def unpad(data):
    data = data[:-data[-1]]
    return data

def decrypt(encrypted, key):
    BLOCK_SIZE = 16
    encrypted = base64.b64decode(encrypted)
    IV = encrypted[:BLOCK_SIZE]
    aes = AES.new(key[0:16], AES.MODE_CBC, IV)
    return unpad(aes.decrypt(encrypted[BLOCK_SIZE:]))


@app.route('/', methods=["GET", "POST"])
def login():
    if request.method == "OPTIONS":
        return 403
    else:
        return render_template("home.html")


@app.route('/encryp', methods=["GET", "POST"])
def encryp():
    if request.method == "OPTIONS":
        return 403
    else:
        if session.get('page_buffer') is None:
            print('here123')
            key = b"gAAAAABfafxf7_uZ--GzUq5GMBc6h"
            temp_=decrypt(str(request.form["fname"]),key)
            temp_1 = decrypt(str(request.form["lname12"]), key)
            session['page_buffer'] = "Yes"
            session['fname']=temp_
            session['lname12'] = temp_1
            fname=session.get('fname')
            password = session.get('lname12')
            #password = decrypt(str(request.form["lname12"]),key)
            return render_template("Cep.html",Name12=fname,Password12=password)
        else:
            print('here')
            fname = session.get('fname')
            password = session.get('lname12')
            # password = decrypt(str(request.form["lname12"]),key)
            return render_template("Cep.html", Name12=fname, Password12=password)




if __name__ == '__main__':
    app.run()

Can Anyone please help me how to detect a user closing a browser or a tab in the flask? Because user should not be viewing the same page once he closes the browser/tab.

JavaScript examples (not working):

The below two are not working because when I'm redirecting to another page these two are getting hit but I don't want that I only want to monitor browser close.

window.addEventListener('beforeunload', function(event) {
        console.log('I am the 2nd one.');
      });
      window.addEventListener('unload', function(event) {
        console.log('I am the 4th and last one…');
      });

if you can suggest a better way to use JavaScript then it is okay for me.

You could try to set a cookie and once the route is accessed again, make Flask check whether such a cookie already exists. If it does, you know the user has been there before. Cookie behavior is largely altered by browser though and can also be manipulated by users easily.

A more reliable and safer way would be to save it in a database, in case you can identify the user by email or something alike.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM