在 JavaScript 中保存用户的 cookie 首选项

问题描述 投票:0回答:1

我有一个简单的 cookies 横幅,如果用户单击“接受”按钮,它会加载谷歌分析脚本。然后它会记住一个月的选择并且不会再出现。但是,如果用户单击拒绝按钮,一旦页面重新加载或访问网站上的另一个页面,它就会再次询问他。

将用户的两个选择都保存到当月是有意义的,这样用户最终就不会被迫接受 cookie。

    // COOKIES START
// ---- ---- Const ---- ---- //
const cookiesBox = document.querySelector(".privacy-container"),
  buttons = document.querySelectorAll(".button");
// ---- ---- Show ---- ---- //
const executeCodes = () => {
  if (document.cookie.includes("SlavicMedia")) {
    // If the cookie is already set, no need to show the cookie consent box
    loadGoogleAnalytics();
    return;
  }
  cookiesBox.classList.add("show");
  // ---- ---- Button ---- ---- //
  buttons.forEach((button) => {
    button.addEventListener("click", () => {
      cookiesBox.classList.remove("show");

      // ---- ---- Time ---- ---- //
      if (button.id == "acceptBtn") {
        document.cookie = "cookieBy= SlavicMedia; max-age=" + 60 * 60 * 24 * 30;
        loadGoogleAnalytics();
      }
    });
  });
};

如何修改代码才能实现所需的功能?

感谢您的宝贵意见

javascript dom cookies
1个回答
0
投票

见下图:

// COOKIES START
// ---- ---- Const ---- ---- //
const cookiesBox = document.querySelector(".privacy-container"),
      buttons = document.querySelectorAll(".button");

// Function to check if a specific cookie is set
const isCookieSet = (cookieName) => document.cookie.split(';').some((item) => item.trim().startsWith(cookieName + "="));

// ---- ---- Show ---- ---- //
const executeCodes = () => {
  // Check if any of the cookies are already set
  if (isCookieSet("SlavicMedia") || isCookieSet("DeclinedSlavicMedia")) {
    if (isCookieSet("SlavicMedia")) {
      loadGoogleAnalytics();
    }
    return;
  }
  cookiesBox.classList.add("show");

  // ---- ---- Button ---- ---- //
  buttons.forEach((button) => {
    button.addEventListener("click", () => {
      cookiesBox.classList.remove("show");

      // Set a cookie for a month based on the user's choice
      let cookieValue = button.id == "acceptBtn" ? "SlavicMedia" : "DeclinedSlavicMedia";
      document.cookie = `${cookieValue}=true; max-age=${60 * 60 * 24 * 30}`;

      // Load Google Analytics if accepted
      if (button.id == "acceptBtn") {
        loadGoogleAnalytics();
      }
    });
  });
};

// Call the function to initialize
executeCodes();
© www.soinside.com 2019 - 2024. All rights reserved.