使用Javascript设置Cookie时遇到问题

时间:2020-10-05 19:39:46

标签: javascript

我正在为网站设置Cookie,但一直无法正确设置它。当我在浏览器(Chrome)上检查DevTools时,总是收到有关未指定SameSite属性的消息。有人可以帮忙吗?

const unsigned int length = inputArray.length();
int previous = inputArray[0];
int next     = inputArray[1];
int maximum  = previous * next;
previous = next;
for (unsigned int i = 1u; i < length; ++i)
{
    next = inputArray[i];
    const int product = previous * next;
    if (product > maximum) maximum = product;
    previous = next;
}

1 个答案:

答案 0 :(得分:0)

我发现我的代码中抛出了多个参考错误。我必须纠正引用变量作为window属性的实例,并且还必须在createCookie中将Unix转换为UTC时间。

const dropCookie = true;
const cookieDays = 14;
const cookieName = "compliance";
const cookieState = "on";
const banner = document.getElementById("cookie-banner");

const displayBanner = () => {
    const main = document.getElementsByTagName("main")[0];

    banner.style.display = "flex";
    main.className += " cookie-banner";

    createCookie(cookieName, cookieState, cookieDays);
}

const closeBanner = () => {
    banner.style.display = "none";
}

const createCookie = (name, value, days) => {
    let cookie = name + "=" + encodeURIComponent(value);
    if (typeof days === "number") {
        let date = new Date();
        let unixDate = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        date = new Date(unixDate);
        const expires = "expires=" + date.toUTCString();
        if (dropCookie) {
            document.cookie = `${name}=${value}; ${expires}; path=/; secure; samesite=lax`
        }
    }
}

最后,我通过将函数保存到变量window.onload,然后在windowInit中调用它来修复了window.onload语句。

const windowInit = () => {
    if (checkCookie(cookieName) != cookieState) {
        displayBanner();
    }
}

window.onload = windowInit();