0

I'm trying to create and store cookie data from an html file using javascript. The first function creates a cookie, and the second is meant to store it.

When the function is called, the console correctly logs the desired information, but the cookie doesn't seem to be created.

JS:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + "; " + expires + "; path=/";
    console.log('Cookie created as ' + name + "=" + value + ". Expiration: " + expires);
}

function readCookie(name) {
    var x = retrieveCookie(name);
    if (x) {
        window.alert(x);
        console.log('Cookie passed to alert menu')
    }
    else {
        console.log('Cookie was undefined and did not return');
    }
}
Scott Shaffer
  • 29
  • 1
  • 7
  • 2
    AFAIK there are no cookies if the webpage is run as local file (`file://` protocol in the URL). To get to use cookies you need to host a page on a server and access as `http://localhost:[port]`. Cookies will work there for `localhost` domain. – Vitalii Jul 07 '21 at 00:11
  • Here's the simplest web server setup I know: https://stackoverflow.com/a/5128451/14596856 – Vitalii Jul 07 '21 at 00:15

1 Answers1

0

Like Vitalii mentioned above, it does need to be run from a server. I ran mine from Windows 10 IIS, and it works great with the code posted above.

Scott Shaffer
  • 29
  • 1
  • 7