0

我正在编写一个 cookie 同意通知,该通知在其功能方面工作正常——当我在主页上并单击“确定”消息以删除横幅时,它会消失并且不会重新显示。

但是,如果我单击以删除站点上任何其他页面上的横幅,当我访问另一个页面时它会再次出现(除非后续页面之一是主页,那么它会在 cookie 的持续时间内消失,因为它应该被点击)。

有谁知道这可能是什么原因造成的?

更新

我注意到的是,如果我点击通知然后刷新页面,在开发工具中,cookie 将“路径”显示为页面名称,即/contact在 Application > Cookies 下,但当然当我将 cookie 应用到主页它应用路径,/然后将覆盖所有站点。

我想我需要一种方法来始终设置/添加 cookie 的任何页面的路径?

在下面的 JavaScript 代码中,基本上添加了一些 CSS 类来淡出/删除横幅,然后添加一个 cookie 以使其保持关闭 12 个月(或直到 cookie 明显被删除)

非常感谢您的帮助

艾米丽

// // COOKIES
var cookieButton = document.getElementsByClassName('cookie-button') [0],
cookieBanner = document.getElementsByClassName('cookie-banner') [0]

cookieButton.addEventListener('click', function() {

    var cookieString = 'CookieConsent=true; expires=';
    var date = new Date();
    var expireDate = date.getTime() + (31536000000);
    date.setTime(expireDate);
    cookieString += date.toUTCString();
    document.cookie = cookieString;

    // fades out cookie banner
    cookieBanner.classList.add('cookie-fade')

})

// prevents cookie showing on next visit
if (document.cookie.split(';').filter(function(item) {
        return item.trim().indexOf('CookieConsent=') == 0
        }).length) {
    
        // prevents cookie notice showing on next visit
        cookieBanner.classList.add('hidden');
}
4

1 回答 1

0

答案是添加; path=/cookieString变量中。

于 2021-08-08T01:12:21.793 回答