Losing cookie (created in javascript) when switching pages

Asked

Viewed 365 times

0

On the HOME page I record a "x" value in cookie.

var dataAtual = new Date();
var expire = new Date();
expire.setDate(dataAtual.getDate() + 1);

document.cookie = "NomeCookie=ValorCookie; expires=" + expire.toGMTString();

When you access the Register page (for example).

var valor = document.cookie;

The value returns all other existing cookies except what I just created. How can I resolve this? (if possible).

Thank you.

2 answers

3


Possible cause of the problem

  • Localhost and Google Chrome / Safari

    You’re using a Safari or Chrome browser with the domain http://localhost, for some reason these browsers in the domain localhost do not allow front-end technologies to add cookies, an attempt solution is to access via http://127.0.0.1, if the problem persists you can try to create a "fake" domain by editing the hosts (if it is in windows) as I explained in this reply:

  • Different domains/sub-domains

    Saving a cookie via javascript on the page http://foo.bar.com and switch to http://bar.com the cookie may not have access

  • Different levels of folder

    If you save the cookie directly it will record at the level of the current folder, suppose you create a cookie on the page http://site/foo/bar/ it will only be accessible the routes that start with foo/bar as an example:

    • http://site/foo/bar/
    • http://site/foo/bar/baz
    • http://site/foo/bar/oi.html

    To work on all levels just change add to your script the path=/, it will say that the cookie can be accessed from this the root (url), or in any page within the same domain, the code should look like this:

    var dataAtual = new Date();
    var expire = new Date();
    expire.setDate(dataAtual.getDate() + 1);
    
    document.cookie = "NomeCookie=ValorCookie; expires=" + expire.toGMTString() + "; path=/";
    

0

A functional example, check if you can fix your problem by following the step by step. I did not identify an error in your script. Functional example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.