Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Javascript cookie in all the pages / globally?

I'm having a huge problem with my code, I am trying to check if a cookie exists, and if it does exist, i dont want it to do anything.

Its working fine on page1, but when i navigate to page2 it overrides the cookie, instead of doing nothing (the pages is from the same website)

Heres my script

function setCookie(c_name, value, exdays) {
    var exdate = new Date();

    exdate.setDate(exdate.getDate() + exdays);

    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());

    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");

    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);

        x = x.replace(/^\s+|\s+$/g,"");

        if (x == c_name) {
            return unescape(y);
        }
    }
}

var omgpost = getCookie("omgpost");

if (omgpost == null || omgpost == "") {
    setCookie("omgpost", "1", 1);
} else {
    alert('cookie installed already');
}

This is working fine, when I don't have the cookie installed and entering this site, I'm adding the cookie, and I'm getting the confirmation message each time I refresh the page1.

But when navigating to page2 its recreating the cookie??? I don't want that! I want the cookie to be there, and can't be changed, only when it has expired, how can I do that?

like image 453
Maryellen Candeew Avatar asked Sep 19 '13 10:09

Maryellen Candeew


People also ask

How do I set cookies to all path?

In your Java server, you should call cookie. setPath("/") before adding it to response. Such cookie will match all request URIs.

Can I set cookie for another path?

You can't access cookies from a different path - otherwise it would be a security hole.

Can JavaScript access all cookies?

You cannot. By design, for security purpose, you can access only the cookies set by your site.

Can JavaScript set cookie for another domain?

You cannot set cookies for another domain.


1 Answers

Set Cookie Path using path=/

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null)
                                 ? "" : "; expires="+exdate.toUTCString())
                                + "; path=/";
    document.cookie=c_name + "=" + c_value;
}
like image 60
gvm Avatar answered Sep 27 '22 18:09

gvm