检查 Cookie 是否存在,如果存在则执行任何操作,如果不存在则设置 cookie

Check for Cookie existance, if yes do whatever, if no set a cookie

所以我想做的是检查 cookie 是否存在(例如 accepted=yes)如果没有设置,它将 return 什么都没有,如果没有,它将执行一些脚本并设置接受 = 是 cookie。这样在下次访问时访问者就不会看到弹出窗口。

var cookie = document.cookie;
if (cookie = accepted=yes) {

} else {
    document.cookie = "accepted=yes";
}

这就是我发现的代码。

您可以使用 getCookie 和 setCookie 函数

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

例子

var user = getCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 365);
    }
  }

参考:W3Schools https://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username