Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read cookie which is created from NewCookie()

I created a cookie using Newcookie() and I can access it thorough the browser as below. Now I need to read the cookie enter image description here

    function getCookieValue(cookieName) {
    console.log("=====getCookieValue=======");
    var name = cookieName + "=";
    var cookies = document.cookie.split(';');
    console.log("=====ALL cookies======="+cookies);
    if (!cookies) {
        return null;
    }
    console.log("=====cookies.length======="+cookies.length);
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        console.log("=====cookies======="+cookies[0]);
        if (cookie.indexOf(name) == 0) {
            return cookie.substring(name.length, cookie.length);
        }
    }
    return null;
}

But by using that method I cant read the cookie. Please advice me on this. Thanks

like image 846
Hasanthi Avatar asked Nov 09 '22 14:11

Hasanthi


1 Answers

Your function is almost perfect. You just need to change this line:

document.cookie.split(';');

You can examine the result in the console by running the above statement: you’ll get an Array with all the cookies but each one of them is preceeded by a whitespace. That’s why the comparison

if (cookie.indexOf(name) == 0)

doesn’t work like expected, because the expected substring doesn’t start at position 0 but at 1.

Therefore, you’ll want to split the list of cookies not by a single semicolon but by a semicolon and a whitespace. I’m not sure about all the browsers out there, so I think the safest way to do it is with a RegExp that checks for an optional whitespace:

document.cookie.split(/;\s?/);
like image 167
Sebastian Simon Avatar answered Nov 15 '22 05:11

Sebastian Simon