1

I have some javascript code that saves a cookie. However, if after saving the cookie, the user opens a new tab, it appears that the cookie is not saved. The new tab is on the same domain.

Here is my cookie setting/getting code:

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

If some javascript calls setCookie('mycookie', 1) and then the user clicks on a link where the _target is set to _blank, the cookie does not load in the new tab. So getCookie('mycookie') will not return 1.

What is the problem here?

speedplane
  • 15,673
  • 16
  • 86
  • 138

2 Answers2

1

I think I figured it out.

I was setting the cookie on one subdirectory and then reading it on another. So I was setting the cookie on www.example.com/foo/ then loading a new tab on www.example.com/bar/ and the cookie was no longer there. I think the setCookie function above does not handle this properly. My solution was to use a more robust cookie library.

speedplane
  • 15,673
  • 16
  • 86
  • 138
0

This could be a security issue, specially if the two pages are on different domains/sub-domains

Read this Question on SO and try to implement

Community
  • 1
  • 1
kishu27
  • 3,140
  • 2
  • 26
  • 41
  • also, a very good read if you want to understand it in detail http://www.quirksmode.org/js/cookies.html – kishu27 Mar 23 '12 at 05:02