How to logout user when he navigates away from your site and disable coming back using the back button on the browser

Hi guys, in Cake 3 how can i stop the user from coming back to my site using the back button on the browser? i tried putting “disableCaching” on the appController but this works only when the user log out. Also i do not want to disable caching on my site. is there a way of achieving this?

What’s the actual use case?

Do you have security concerns? Like for instance a banking website, where you don’t want users to stay logged in unless they’re actually on the page, doing something?

As far as I know, there’s no real way to tell when the user leaves a page. But you could save the log in time to a session and update it whenever the user is doing something (either via ajax or on every request).

After, say, 10 minutes of inactivity, when the user makes a new request, he should be logged out and receive a notification letting him know why.

Is that what you’re looking for?

Hi Ali and thank you for the reply.

Yes it is for security concern like a banking website. We do not just want somebody on leaving the website without logging out and be able to comeback using the back button on the browser. We want to log the user out if he leaves the site and ALWAYS send him back to the login page.

I am not sure how the bank does it but i think they got it to work. I hope you understand better what i am trying to achieve.

Thank you

Yeah, as far as I know a timeout is the only way then.

It’s not really possible to log the user out when he leaves the page, since there’s not really a reliable “on tab closed” event in JS.

You could use long polling or web sockets to send data to the server in order to let it know that the user is active on the page and then use a timeout on the server to log the user out once no data is sent for a certain period of time (because the user closed the window). That’s probably as close as you could get to what you need.

As for the back button: Browsers tend to cache form data when switching back and forth, but you could use the pageshow event to reset the form on page load. More on that here:

Thank you very much. I will look into this.

seems like this is more of a javascript event listener…

window.onbeforeunload = function(event) {
// call the cakephp rest end point to logout
// like: http://localhost/users/logout
}

wish you luck!

Hi tdatu,

thank you for the suggestion. I tried that but it does not work 100%. It logs out user even if he tries to go to another page on the same site.

im not sure if this is browser specific, but mozilla is pretty reliable:
https://developer.mozilla.org/en-US/docs/Web/Events/DOMWindowClose