Please see my answer recently about a similar Session issue
Redirect to login page when the Session is Expired.[
^]
The problem with your code is that it's all client side javascript - you haven't tested for the session anywhere, you'd need to call back to the server in order to access that.
As I explained in my answer, I really don't see the need for any of this. You can achieve correct behaviour of web pages by correctly setting pages to be non-cacheable