Javascript – Accessing Cookies Created In Server Side from Javascript

asp.netccookiesjavascriptsession

I have created a usercontrol which i am using throughout my application to auto sign out users upon session timeout occurs. For that I am using a cookie variable.
I need to reset the cookie variable once a postback occurs as it means the user is active. The following code bit sets the expiry time which will be saved to a cookie "express"

DateTime date = DateTime.Now;
LoginDate = date.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z","");
int sessionTimeout = Session.Timeout;
dateExpress = date.AddMinutes(sessionTimeout);
ExpressDate = dateExpress.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z", "");

HttpCookie cookie = Request.Cookies["express"];
if (cookie == null)
{
  cookie = new HttpCookie("express");
  cookie.Path = "/somepath/";
  cookie.Values["express"] = ExpressDate;
}
else
{
  cookie.Values["express"] = ExpressDate;
}

I am using the following javascript code to retrieve the cookie set from the server side in the client side timer which check continuously if the session is expired

<script type="text/javascript">
var timeRefresh;
var timeInterval;
var currentTime;
var expressTime;

expressTime = "<%=ExpressDate %>";
currentTime = "<%=LoginDate %>";
//setCookie("express", expressTime);
timeRefresh = setInterval("Refresh()", 10000);

// Refresh this page to check session is expire or timeout.
function Refresh() {

var current = getCookie("express");
alert(current);
}

// Retrieve cookie by name.
function getCookie(name) {
    var arg = name + "=";
    var aLen = arg.length;
    var cLen = document.cookie.length;
    var i = 0;
    while (i < cLen) {
        var j = i + aLen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return;
}

function getCookieVal(offSet) {
    var endStr = document.cookie.indexOf(";", offSet);
    if (endStr == -1) {
        endStr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offSet, endStr));
}

But I am always getting a undefined value for the cookie from the client side.

PS: I also tried using a session variable created at the server side and accessing it from javascript but eventhough it reads the session value it only read the first value assigned at the page load where I want to get the session value at the next postback

I am setting the session express in the pageload()

 Session["express"] = ExpressDate;

Then Tried to access it from javascript like this

function Refresh()`
{
var current = '<%=Session["expiry"].ToString()%>'
alert(current) // This always return the first value assigned during page load
}`

Any help is much appreciated

Best Answer

I suspect that the path might create the problem. When you set path to /somepath/ the cookies can be access in client side only on the requests which has the /somepath/.

For example,

You are requesting a page http://example.com/somepath/login and setting cookies at server with the path value as /somepath/login.

Next time, you are reuesting a page http://example.com/otherpath/done and trying to access the cookie in client side. Since you set the cookies in the path /somepath/login at server, you will not get those cookies with this request.

So make sure you have set the proper path for cookies or dont set it so that it becomes / and the cookies set on this path would be accessible in all request under the same domain http://example.com.