Javascript 离开页面后删除了 cookie

Javascript cookie removed after leaving page

我正在尝试在用户第一次访问网站页面时创建一个 cookie,并将路径名存储为该页面的 cookie 值以供记录。

我正在尝试通过在页面加载时创建一个名为 GenerateCookie 的函数来做到这一点。

此函数然后检查 cookie reportingpage 是否存在,如果不存在则创建 cookie。我希望在会话结束之前该值保持不变。我正在尝试记录访问的第一页。因此,例如,如果用户访问 /testing-page/ 我希望 cookie 值保持 /testing-page/ 即使他们退出页面并访问其他页面,因为那是访问的第一个页面。

目前,cookie 是按预期创建的,路径名值也是预期的,但每次我退出页面并访问新页面时,cookie 都会被删除并与其他页面一起设置 pathname价值。我试图通过在设置 cookie 时包含 path= 属性来解决此问题,但这没有效果。

如何创建 cookie 并在整个会话中保持相同的值,直到 tab/browser 关闭?

这是我的代码片段:

  GenerateCookie();


    function GenerateCookie() {

     // if cookie does not exist, create cookie reporting page

        if (document.cookie.indexOf('reportingpage=') == -1) {

            console.log('no cookie')

            document.cookie = "reportingpage=https://www.testing.com" + window.location.pathname + "; path=/"

        } else {

            // if cookie exist, get value
             console.log('cookie exist')

            const name = "reportingpage"

            const match = document.cookie.match(RegExp('(?:^|;\s*)' + name + '=([^;]*)')); 

            console.log(match[1], 'value')
        }

    }

在某人的计算机上存储一百个 cookie 确实是不道德的,尤其是当它用于跟踪他们的页面访问时。如果我访问了一个站点并突然有大量 cookie 要删除,我会非常生气。但也许你有充分的理由,所以如果你真的必须这样做,那么使用 localStorage 而不是 cookies。

sessionStorage.setItem('someKey', window.location.pathname)