我想知道是否可以使用Javascript创建仅会话cookie。关闭浏览器后,应删除Cookie。
我无法在服务器上使用任何内容,因为该网站仅是HTML ...因此未使用服务器端脚本。
我在这里阅读有关此内容:http : //blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/ 但我找不到关于此的更多信息...所以我想知道这种方法是否可靠。
我想知道是否可以使用Javascript创建仅会话cookie。关闭浏览器后,应删除Cookie。
我无法在服务器上使用任何内容,因为该网站仅是HTML ...因此未使用服务器端脚本。
我在这里阅读有关此内容:http : //blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/ 但我找不到关于此的更多信息...所以我想知道这种方法是否可靠。
Answers:
对,那是正确的。
expires无论是用JavaScript还是在服务器上创建,不放置部件都会创建会话cookie。
sessionStorage在这种情况下,更简单的解决方案是使用:
var myVariable = "Hello World";
sessionStorage['myvariable'] = myVariable;
var readValue = sessionStorage['myvariable'];
console.log(readValue);
但是,请记住,sessionStorage所有内容都保存为字符串,因此在处理数组/对象时,可以使用JSON来存储它们:
var myVariable = {a:[1,2,3,4], b:"some text"};
sessionStorage['myvariable'] = JSON.stringify(myVariable);
var readValue = JSON.parse(sessionStorage['myvariable']);
只要打开浏览器,页面会话就会持续,并在重新加载和还原页面后继续存在。在新标签或窗口中打开页面将导致启动新会话。
因此,当您关闭页面/选项卡时,数据将丢失。
SessionStorage只能提供一种client-only解决方案,而不能在服务器端访问这些值。在许多服务器端框架(例如ASP.Net和PHP)中,我们希望不使用隐藏字段等即可轻松访问我们可能存储的客户端值,然后cookie成为更好的解决方案,因为cookie会自动发送到服务器端。
要使用Java脚本创建仅会话cookie,可以使用以下内容。这对我有用。
document.cookie = "cookiename=value; expires=0; path=/";
然后获得如下的cookie值
//get cookie
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
//write your script
}
//function getCookie
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.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) != -1) return c.substring(name.length, c.length);
}
return "";
}
可以支持IE,我们可以完全退出“过期”并可以使用它
document.cookie = "mtracker=somevalue; path=/";
将以下代码用于安装会话Cookie,它将在浏览器关闭之前起作用。(确保不关闭标签页)
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 false;
}
if(getCookie("KoiMilGaya")) {
//alert('found');
// Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again..
} else {
//alert('nothing');
// Display popup or anthing here. it shows on first visit only.
// this will load again when user closer browser and open again.
setCookie('KoiMilGaya','1');
}