Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The following web page is suppose to read and write a cookie. It works in FireFox but
not in Chrome.
HTML
<!DOCTYPE html>
<html>
<head>
<script>

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
} 
</script>
</head>
<body onload="checkCookie()">
</body>
</html>


What I have tried:

I have tired to debug it by printing things out with alert. I got this code from W3 Schools. I am thinking that I need to give it a path on where to store the cookie.

Bob
Posted
Updated 23-Mar-18 3:06am
Comments
W Balboos, GHB 23-Mar-18 7:37am    
Path where you need to put the cookies? No - cookies are put in a browser determined location.   Mozilla: the cookie jar; IE, each was a file; Chrome: whatever.

Check the cookie filter settings on Chrome. Also, are your cookies being set for your current site or for a third party site? That matters.
F-ES Sitecore 23-Mar-18 9:53am    
The code works fine in Chrome for me, the issue is probably with something else about your setup.

1 solution

I checked in the browser and my page is not setting a cookie. There are other cookies being set.

Here are my cookies settings:
Cookies
Allow sites to save and read cookie data (recommended)
Keep local data only until you quit your browser
Block third-party cookies


In the browser there is a slide bar next to each of the three items. For the first one, the slide bar is to the right and it is the color blue. For the next two, the slide bar is to the left. Are these settings right?

Bob
 
Share this answer
 
Comments
Richard Deeming 23-Mar-18 12:50pm    
If you want to reply to a comment, click the "Reply" button next to the comment.

DO NOT post your reply as a "solution".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900