NetManiac

Witold Rugowski on web20 wave with Ruby on Rails

Cookies and port in host’s location

Posted on November 10, 2006 - Filed Under JavaScript, RubyOnRails

I’ve just discovered setting cookies with port number in domain does not sets cookie (at least in Flock).

Let’s assume we have Rails application web server (default on TCP 3000 port). And in JS we use to set cookie something similar to:


function setCookie(name, value, expires, path, domain, secure) {
    cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toUTCString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = cookie+";";
}

setCookie("rnsloc",
    map.getCenter().lat()+"-"+map.getCenter().lng()+ "-" +map.getZoom(),
    date,
    '/',
    location.host )

Well it does not sets cookie. Why? Using Firebug’s JS console it takes minutes to find out.

>>> document.cookie="rnsloc=test1; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1;"
"rnsloc=test1; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1;"

>>> document.cookie
"rnsloc=test1; _session_id=f9be28b6447cdf32979ff173dd30cd3d"

>>> document.cookie="rnsloc=test2; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1:3000;"
"rnsloc=test2; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1:3000;"

>>> document.cookie
"rnsloc=test1; _session_id=f9be28b6447cdf32979ff173dd30cd3d"

Well as You can see after adding port to host rnsloc value does not changes – setting cookie fails silently. Why it matters? Beacouse many examples show how to set cookie using location.host property. It happens that it contains port number if it is present in URL. So You need to use something like location.host.split(":")[0]. I hope it does never contain http:// or https:// header.

Popularity: 4% [?]

Hits for this post: 4679

Similar Posts

Comments

Leave a Reply