我有一个cookie,用于保存一些相当良性的数据,我用它来检查Changelog模式窗口是否应出现在页面上。当我加载页面时,根本没有cookie。该项目在IIS上运行,使用带有ASP和MVC的.NET Core 2.2。因此,我执行以下操作:
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');
...
...
发生了什么事
“ dontPersistChangelog = false; changelogVersion = 0; path = /; expires = Tue,2022年9月6日星期三13:54:33 GMT”
为了很好,下面是设置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();
}
这是令人困惑的部分;当我关闭浏览器并启动浏览器备份时,就会发现实际的cookie存在。我使用浏览器中的控制台进行了检查。就像它被删除并消失了一样。我的印象是document.cookie
与会话Cookie 不相同吗?它可以在单独的会话中持续存在吗?
我尝试了有无有效期的cookie。 cookie会以任何一种方式删除。当我在Visual Studio中运行项目或在IIS上部署版本时,都会发生这两种情况。
我可能做错了什么?
答案 0 :(得分:1)
请参见https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
我不认为您对document.cookie的调用正在更新现有cookie的属性。 Cookie的属性以分号分隔并存储为字符串。
因此,您像这样设置一个cookie:
function resetOnce() {
document.cookie = "doSomethingOnlyOnce=; expires=Thu,01 Jan 2050 00:00:00 GMT";
}
对于上述功能,
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();}