user961627
user961627

Reputation: 12747

JavaScript code for cookie not working in Chrome

The following code works fine in FF:

var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = "c_odi" + "=" + $('#orderdetailid').val() + expires + "; path=/";

But not in Chrome. When I'm using Chrome and I do document.cookie in the console to view cookies, the c_odi cookie isn't there. But when I do the same in FF, it is. How can we make cookies work in Chrome? The cookies that were added by PHP are fine, but not this one in JavaScript, and I do need to add this cookie via JavaScript at this point.

Upvotes: 23

Views: 43767

Answers (6)

Ivar van Wooning
Ivar van Wooning

Reputation: 183

When opening HTML files in chrome as file://, as a workaround, use the session storage instead of cookies. Session storage does not have the exact same functionality as cookies of course, but it may be helpful in some cases.

sessionStorage.setItem("some_property", "true"); sessionStorage.getItem("some_property");

Upvotes: 1

Roman Hocke
Roman Hocke

Reputation: 4239

This problem can occur if You open Your code as file:///C:/.../xxx.html instead of http:// localhost/xxx.html. Chrome doesn't save cookies (because there is no domain and no http communication) in file:// case.

Few links of interest:

Upvotes: 55

Deepak Ranganathan
Deepak Ranganathan

Reputation: 51

Chrome doesn’t store cookies from the pages which are loaded from local file system. For example if you are accessing a HTML file in chrome browser from local file system(ex: file:///C:/Users/deepak.r/Desktop/test.html), cookies are not supported.

Upvotes: 4

Dean
Dean

Reputation: 1

Make sure your address bar url matches the domain. In Chrome if you set domain=www.site.com and then test your page in the browser missing out the www. it won't work.

Upvotes: 0

alexander.biskop
alexander.biskop

Reputation: 1862

Seems like it's working for me:

enter image description here

http://jsfiddle.net/rQEnF/3/

At least the cookie shows up in dev tools, as you can see. However, I replaced the jQuery selector $('#orderdetailid').val() with a constant value, as you can see. Is there something wrong with that value or the element containing the value maybe?

Upvotes: 0

sbgoran
sbgoran

Reputation: 3541

Try to replace this line:

document.cookie = "c_odi" + "=" + $('#orderdetailid').val() + expires + "; path=/";

with this one:

document.cookie = "c_odi" + "=" + escape($('#orderdetailid').val()) + expires + "; path=/";

You would have to use unescape when you try to read value, but you'll menage when time comes :)

Upvotes: 0

Related Questions