kkapsner
Super Moderator
Da das Thema immer wieder hier auftaucht will ich hier mal an exponierter Stelle meine Cookie-Verwaltung darstellen:
Die Anwendung ist recht einfach:
- versucht das mal mit den üblichen Cookie-Skripts!
PS: Kommentare, Verbesserungen, Fragen dazu gerne gesehen.
Code:
var cookie = {
// return value if the name is not stored in document.cookie
defaultReturnValue: null,
// this should be true if you want to be sure, that all your special characters (like ä, ö, ü, ², µ, €, \n, \t, ...) are treated in a safe way - but with this option enabled the string stored in the cookie can get much longer
secureEncoding: true,
update: function(){
var cString = document.cookie.toString();
var werte = cString.split(";");
for (var i = 0; i < werte.length; i++){
var wert = werte[i].split("=");
var name = this.decode(wert[0].replace(/^\s+/, ""));
var value = this.decode(wert.slice(1).join("="));
this[name] = value;
}
return this;
},
getValue: function(name){
this.update();
if (typeof(this[name]) == "string") return this[name];
return this.defaultReturnValue;
},
setValue: function(name, value, att){
//att can contain this attributes: expire, domain, path, secure
if (!att) att = {};
var insert = this.encode(name) + "=" + this.encode(value);
if (att.expire && att.expire.constructor == Date){
insert += ";expires=" + att.expire.toGMTString();
}
if (typeof(att.expire) == "string" && att.expire){
insert += ";expires=" + att.expire;
}
if (typeof(att.domain) == "string" && att.domain){
insert += ";domain=" + att.domain;
}
if (typeof(att.path) == "string" && att.path){
insert += ";path=" + att.path;
}
if (att.secure){
insert += ";secure";
}
document.cookie = insert + ";";
return this;
},
deleteValue: function(wert, att){
if (!att) att = {};
att.expire = new Date(0);
this.setValue(wert, "", att);
if (typeof this[wert] == "string") this[wert] = false;
return this;
},
encode: function encode(str){
if (this.secureEncoding) return str.replace(/([^a-z0-9])/ig, function(m, f){return "+" + f.charCodeAt(0).toString(36) + "/"});
return str.replace(/(%|=|;)/g, function(match, f){return "%" + {"%": "%%", "=": "%_", ";": "%."}[f];});
},
decode: function decode(str){
if (this.secureEncoding) return str.replace(/\+([a-z0-9]+?)\//g, function(m, f){return String.fromCharCode(parseInt(f, 36));})
return str.replace(/%(%|_|.)/g, function(match, f){return {"%": "%", "_": "=", ".": ";"}[f];});
}
};
Die Anwendung ist recht einfach:
Code:
var name = "³²{};=,&%+/";
var value = ";=;()~ÄÜä\\}]/()";
cookie.setValue(name, value);
var newValue = cookie.getValue(name);
alert(value + " -> " + newValue + ":" + (newValue == value));
cookie.deleteValue(name);
alert(cookie.getValue(name));
PS: Kommentare, Verbesserungen, Fragen dazu gerne gesehen.
Zuletzt bearbeitet: