Missing cookie (created in javascript) while switching pages

0

On the HOME page, I write an "x" value in a cookie.

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

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

When accessing the Registration page (for example).

var valor = document.cookie;

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

Thank you.

    
asked by anonymous 23.06.2017 / 17:20

2 answers

3

Possible cause of the problem

  • Localhost and Google Chrome / Safari

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

  • Different domains / sub-domains

    If you record a cookie via javascript on the http://foo.bar.com page and change to http://bar.com the cookie can not have access

  • Different levels of folder

    If you save the cookie directly it will write to the current folder level, suppose you create a cookie on the page http://site/foo/bar/ it will only be accessible to routes that begin with foo/bar such as:

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

    In order to work on all levels, just change the path=/ to your script, it will say that the cookie can be accessed from this root (from the url), ie on any page within the same domain, 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=/";
    
23.06.2017 / 17:33
0

A working example, make sure you can solve your problem by following the step-by-step instructions. I did not identify an error in your script. Functional sample

    
23.06.2017 / 17:29