Reputation: 5709
I have a cookie that saves some fairly benign data I use to check if a Changelog modal window should appear on a page or not. When I load a page there is no cookie at all. The project runs on IIS, using .NET Core 2.2 with ASP and MVC. So I do the following:
function showChangelog(override = false) {
let newestEntryId = getNewestChangelogVersion();
let cookieEntryId = getCookieChangelogVersion();
if (newestEntryId > cookieEntryId) {
setCookieDetails(false, newestEntryId);
cookieEntryId = newestEntryId;
}
let changelogPersistence = getCookieChangelogPersistence();
if (changelogPersistence === false || override === true) {
let modalBody = $('#changelogModalBody');
...
...
Here is what happens:
"dontPersistChangelog=false; changelogVersion=0; path=/; expires=Tue, 06 Sep 2022 13:54:33 GMT"
For good measure, here is the code that sets the cookie:
/**
* Used to set the website cookie for the changelog window.
* @param {boolean} persistence Whether the changelog should not persist (true) or persist (false)
* @param {number} version What version of the log is being put in the cookie.
*/
function setCookieDetails(persistence, version) {
let expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 999);
let persistChangeLog = 'dontPersistChangelog=' + persistence;
let changelogVersion = 'changelogVersion=' + version;
document.cookie = persistChangeLog;
document.cookie = changelogVersion;
document.cookie = 'path =/';
document.cookie = 'expires=' + expirationDate.toUTCString();
}
Here is the puzzling part; The actual cookie seizes to exist when I close the browser and start the browser back up. I checked using the console in the browser. It's like it gets deleted and its gone. I was under the impression that document.cookie
was not the same as a session cookie? That it could persist through separate sessions?
I tried the cookie with and without an expiration date. The cookie is deleted either way. This both happens when I run the project in Visual Studio or the deployed version on my IIS.
What am I potentially doing wrong?
Upvotes: 0
Views: 526
Reputation: 154
See https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
I don't think your calls to document.cookie are updating properties of an existing cookie. A cookie's properties are semicolon separated and stored as a string.
So you set up a cookie like so:
function resetOnce() {
document.cookie = "doSomethingOnlyOnce=; expires=Thu,01 Jan 2050 00:00:00 GMT";
}
So for your function above:
function setCookieDetails(persistence, version) {
let expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 999);
let persistChangeLog = 'dontPersistChangelog=' + persistence;
let changelogVersion = 'changelogVersion=' + version;
document.cookie = persistChangeLog + ";path =/;expires=" + expirationDate.toUTCString();
document.cookie = changelogVersion + ";path =/;expires=" + expirationDate.toUTCString();}
Upvotes: 1