Link to home
Start Free TrialLog in
Avatar of ITsolutionWizard
ITsolutionWizardFlag for United States of America

asked on

Read Cookie value in JS

Do you see any wrong with the source codes below? I try to capture cookie name/value in javascript. The cookie is generated from MVC.net app.
You can see attach screenshot.
Thanks


<script>
    $(window).on('load', function () {
        var value = readCookie('.ASPXAUTH');
        alert("Cookie Name: " + value);
    })

    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;
    }
</script>

Open in new window

cookie.jpg
Avatar of ITsolutionWizard
ITsolutionWizard
Flag of United States of America image

ASKER

I also set <httpCookies httpOnlyCookies="false"  /> on webconfig
anyone helps?

Avatar of ste5an
Do you get any error?

See Document.cookie. The key and the value part may be surrounded by whitespaces. These includes not only spaces.

And I would start debugging with something simpler. E.g.

function readCookie(name) {
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        if (ca[i].indexOf(name) >= 0)
            return ca[i];
    }

    return null;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial