【发布时间】: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