Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 601
user961627 Avatar asked Mar 13 '13 12:03

user961627


People also ask

How do I enable cookies in JavaScript?

At the top right corner, click Settings and more , then choose Settings. Select Cookies and site permissions. Click Manage and delete cookies and site data, then turn ON Allow sites to save and read cookie data (recommended). Select JavaScript under Site permissions, then turn ON Allowed (recommended).

Can cookies be set by JavaScript?

JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.


1 Answers

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:

  • https://gist.github.com/shellscape/02d3a97031e7afdf99d2642f93d59486
  • Setting Cookies using JavaScript in a local html file
  • https://bugzilla.mozilla.org/show_bug.cgi?id=536650
  • https://datatables.net/forums/discussion/46255/save-state-to-cookie-in-file-protocol
like image 96
Roman Hocke Avatar answered Oct 11 '22 04:10

Roman Hocke