【问题标题】:How To set Cookie To expire when tab is closed如何设置 Cookie 在选项卡关闭时过期
【发布时间】:2019-05-16 02:48:24
【问题描述】:

我正在尝试为我的媒体播放器here 创建一个会话 cookie,以跟踪使用情况和其他事情,下面的代码和代码 sn-p 根本没有创建它,(顺便说一下,我'正在使用一个脚本使用参数创建多个 cookie,并希望保持这种状态以防止冗长的脚本)

我已经尝试了很多网站上提供的答案,但它们不起作用,它们只会导致同样的问题

//script to create the cookies
function setCookie(cname,cvalue,exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires=" + d.toGMTString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
//for the cookie that makes the name, not part of the question
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 "";
}
// also for the name
function checkCookie() {
  var user=getCookie("username");
  if (user != "") {
    document.getElementById("display").innerHTML = "Welcome back " + user
  } else {
  document.getElementById("display").innerHTML = "Please enter your name in The prompt at the top of your screen!";
     user = prompt("Please enter your name:","");
     if (user != "" && user != null) {
       setCookie("username", user, 30);
     }
  }
}
window.onload = checkCookie()
//for the session
window.onload = createsession()

function createsession(length){
    var sessionnumber = Random rand = new Random();

long drand = (long)(rand.nextDouble()*10000000000L);
    setCookie("session", sessionnumber);
};
window.onbeforeunload = function(){
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
};

我想要的是让脚本创建一个在浏览器会话结束时过期的 cookie,同时能够保持其他脚本相同以允许我创建多个 cookie 而不会复制那些处理脚本

【问题讨论】:

  • 在会话开始时使 cookie 过期。实际上,为什么要删除 cookie?当您开始新会话时,它将被覆盖
  • 欢迎来到 StackOVerflow。您能否确认正在创建 cookie?当您卸载文档时,我也没有看到您尝试使 cookie 过期。请提供一个最小、完整和可验证的示例:stackoverflow.com/help/mcve
  • @DCR,我希望它们被删除的原因是应用程序可以跟踪用户是否仍然处于活动状态,但现在我考虑了一下,我不希望删除 cookie,但现在我希望在用户处于非活动状态一段时间后将其删除(在没有音乐播放的情况下处于非活动状态)
  • @Twisty 通常,如果我没有设置过期日期,它会在浏览器关闭时过期。这通常对我有用,我不知道为什么它现在不起作用。 >:(

标签: javascript jquery html cookies


【解决方案1】:

我为测试创建了以下小提琴:https://jsfiddle.net/Twisty/toxjLmd8/10/

我添加了一些东西来增加控制台中的信息。当我检查页面并查看存储时,我可以看到session cookie 和username cookie。如果我刷新,系统会提示我再次输入名称。所以它似乎按预期工作。

$(function() {
  function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    if (exdays == undefined) {
      exdays = 1;
    }
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    console.log("Set Cookie: " + cname + "=" + cvalue, expires);
    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 false;
  }

  function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
      $("#display").html("Welcome back " + user);
    } else {
      $("#display").html("Welcome, please enter your name.");
      user = prompt("Please enter your name:", "");
      if (user != "" && user != null) {
        setCookie("username", user, 30);
      }
    }
  }

  function newSession() {
    var sessionnumber = Math.random() * 10000000000.0;
    console.log("New Session: " + sessionnumber);
    setCookie("session", sessionnumber, 0.0125);
  }

  function checkSession() {
    if (getCookie("session") == false) {
      newSession();
    }
    console.log("Current Session: " + getCookie("session"));
  }

  window.onbeforeunload = function() {
    console.log("Closing - Expire 'username' Cookie");
    setCookie("username", "", 0);
  };

  window.onload = checkCookie();
  window.onload = checkSession();
});

设置过去的日期或当前的日期和时间应该让浏览器立即使 cookie 过期并删除它。设置没有过期日期的 cookie 可能会在不同的浏览器中产生意想不到的结果。如果未设置日期,它应该在会话结束时过期(预期行为),但浏览器可能会看到它已经过期(仍然很好)或永远不会过期(真的不好)。并非所有的浏览器都是一样的。

此外,如果未触发 onbeforeunload 回调,则 cookie 不会过期,但每个 checkCookie() 将保持活动 30 天。您可以将 cookie 设置为在 20 分钟后过期(0.0125 天)。这就是在服务器端处理会话的方式。如果套接字关闭并且会话空闲 20 分钟(会话空闲超时的默认值),则会话数据将被丢弃。

希望这会有所帮助。

【讨论】:

  • 我刚刚尝试过,它完全有效,这是我尝试过的最佳解决方案。谢谢:-)
  • @ZacharyCross 太棒了!希望您将其标记并投票作为答案。
猜你喜欢
  • 2014-08-14
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 2012-05-25
  • 2011-10-07
  • 1970-01-01
  • 2021-08-04
相关资源
最近更新 更多