Azazel Azazel - 2 years ago 57
HTML Question

HTML cookie don't create

I'm having problem of creating a cookie, I have this code:

window.onload = function() {

var value = readCookie('username');
if(value == null){
document.cookie = "username=Bob; expires=Thu, 18 Dec 2016 12:00:00 UTC";


function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
return null;

When the page load I check if the cookie exists, if it doesn't, I pop up an alert saying that is null, then I create the cookie, but every time I load the page it always says its null. Now the problem is in the creation of the cookie or in the readCookie function. I can't find why this doesn't work.

So in google Chrome it won't work, but in internet explorer works perfectly, someone knows why? I would like to work in all browsers.

Answer Source

When I create an HTML page using that code and run it in a normal test environment, the problem you describe does not occur. It alerts null on the first load and Bob on the second load.

If, however, I tell the browser to load the page from file:///Users/david/tmp/jgfklgjkl/index.html instead of my test server at http://localhost:7007/, then it always alerts null.

Cookies are associated with a hostname, and you have to load the page over HTTP in order to use them.

You are presumably loading them from a local file, and that is where the problem lies, not with your code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download