Reputation: 3896
I am using a simple javascript code like this to play around with cookies
var theCookie = "login = ScottPilgrimVStheWorld";
document.cookie=theCookie;
alert(document.cookie);
I have just a simple html
page with a body, a header and this javascript code.
Problem is , this is working in IE and FF but not in GC 33.0.1750.154 m. I get an empty alert box. I took a glance at the GC settings and found nothing on blocking/unblocking Cookies. What is happening? Any tips?
Thanks in advance.
EDIT
Here is another function for reading cookies
function getCookie(searchName)
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var cookieCrumbs = cookies[i].split("=");
var cookieName = cookieCrumbs[0];
var cookieValue = cookieCrumbs[1];
if (cookieName == searchName)
{
return cookieValue;
}
}
return false;
}
"The JavaScript Anthology 101 Essential Tips, Tricks & Hacks" by James Edwards and Cameron Adams, Copyright © 2006 SitePoint Pty. Ltd., pp145-146
Upvotes: 0
Views: 130
Reputation: 17258
No spaces are allowed in the assignment string added to the cookie jar. Try
var theCookie = "login=ScottPilgrimVStheWorld";
Tested on chrome 33 ( 33.0.1750.154 ).
edit:
chris97ong is right in his claim that you need additional logic to extract a single cookie from the cookie jar document.cookie
. if you need that, use his code or match against a regex:
var mycookie = document.cookie.replace(/(^|;)login=([^;]+)(;|$)/, "$2");
Upvotes: 1
Reputation: 7070
Try modifying variable theCookie
:
var theCookie = "login=ScottPilgrimVStheWorld;";
We must do this because as stated in W3Schools, the template for a cookie is
[cookie-name]=[cookie-name-val]; [Next is optional] expires=[expiry_date]
.
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
So you change your alert to something like this:
alert(getCookie("login"));
Hope that helped.
Upvotes: 1