Search code examples
javascripthtmljspback-button

Disable browsers back button if the session is invalidated


I'm working on JSP. I know there are many posts regarding this topic but nothing is working for me. I have a login page which leads to a welcome page. The session is invalidated when the user clicks on logout and is then redirected to the login page. But if the user clicks the browsers back button he is again taken to the welcome page, although if he presses any other button or refreshes the page he will be taken to the login page because the session has expired. But I don't want the user to be able to access the welcome page by clicking the browsers back button once he's logged out. I tried using the following:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

but it's not working.

I tried using:

window.history.forward(1);

it works fine, but it leads to another problem. If the user logs in and is taken to the welcome page. then the user presses a button let's say "show user details" and the user is taken to the "show user details" page. now if the user clicks the back button to go back to the welcome page. He stays on the same "show user details" page, because of the window.history.forward(1) on the welcome page.

I want that the user should be able to use the browsers back button if the session is valid. If the session is invalid he should not be able to use the browsers back button.


Solution

  • This is working perfectly. i used the following to clear the cache. and i'm invalidating the session in logout.jsp, when clicked, it checks for some token attribute (which is set when the user logs in), and if it doesn't find it, it redirects to the login page.

    <%
    
    response.setHeader("Cache-Control","no-cache");
    response.setHeader("Cache-Control","no-store");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader ("Expires", 0);
        if(session.getAttribute("token")==null){
        response.sendRedirect(request.getContextPath() + "/LogOut.jsp");
    
    }
    %>
    

    thanks for the suggestion though. I will certainly put it into action. every help and suggestion is appreciated.