P
P
partyzanx2020-08-29 13:42:07
Node.js
partyzanx, 2020-08-29 13:42:07

How to delete a session when the site closes?

When entering the site, the user checks the box to delete the session when the site is closed or not.
If I delete it, then the following code works for me on the client

window.addEventListener("unload", () => {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', '/user/sessionDestroy');
    xhr.send();
});


This code runs a get request

router.get('/sessionDestroy', async (req, res) => {
    try {
        if (req.session && req.session.user) {
                const candidate = await User.findOne({email: req.session.user.email})
                if (candidate.remainInSystem) {
                    // console.log('remainInSystem');
                    return 
                }
        } 
        console.log('deleting session');
        req.session.destroy();
        res.status(200).send('ok');
    } catch (error) {
        console.log(error);
    }
})


The problem is that this scheme works correctly only in Opera, and in other browsers the session is deleted when the page is reloaded. What is the best way to implement the system "deleting a session if the user so wants"?

The strangest thing is that the event...

window.addEventListener("unload", () => {
 
});


...in i.browser, firefox fires when the page has loaded, not when the page is closed.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question