Accueil > > > LES COOKIES ET JAVASCRIPT
LES COOKIES ET JAVASCRIPT
Information sur la source
Description
Comme la propriété cookie de l'objet document de l'objet window (window.document.cookie) est assez complexe a mettre en place et à exploiter, je vous propose cet objet. (compatible IE, FF, Opera, Google chrome)
Source
- function Cookie(sName, sFormat, sValue)
- {
- var argc = Cookie.arguments.length;
-
- /*attributes*/
- if(sFormat != "GET" && sFormat != "get")
- {
- this.name = sName;
- this.format = sFormat;
- this.value = (argc > 2) ? (sValue) : ("");
- date_exp = new Date();
- date_exp.setTime(date_exp.getTime()+((argc > 2) ? (iExpiration) : (365*24*3600)));
- this.expiration = date_exp;
- if(this.format == "JSON"){this.value = this.name+'={anonymousAttribute:""};';}
- if(argc > 1){this.saveCookie();}
- }
- if(sFormat == "GET" || sFormat == "get")
- {
- this.name = sName;
- this.value = this.getCookie(sName);
- date_exp = new Date();
- date_exp.setTime(date_exp.getTime()+((argc > 2) ? (iExpiration) : (365*24*3600)));
- this.expiration = date_exp;
- this.format = (/=\{.+\};/i.test(this.value)==true) ? "JSON" : "STR";
-
- }
- }
-
- /* Methodes */
- Cookie.prototype.getCookieVal = function(offset)
- {
- var endstr=document.cookie.indexOf (";", offset);
- if (endstr==-1)
- endstr=document.cookie.length;
- return unescape(document.cookie.substring(offset, endstr));
- };
- Cookie.prototype.getCookie = function (name)
- {
- var arg=name+"=";
- var alen=arg.length;
- var clen=document.cookie.length;
- var i=0;
- while (i<clen)
- {
- var j=i+alen;
- if (document.cookie.substring(i, j)==arg)
- {
- return Cookie.prototype.getCookieVal (j);
- }
- i=document.cookie.indexOf(" ",i)+1;
- if (i==0){break;}
- }
- return null;
- };
- Cookie.prototype.saveCookie = function ()
- {
- var expires= this.expiration;
- document.cookie=this.name+"="+escape(this.value)+((expires==null) ? "" : ("; expires="+expires.toGMTString()))+""+""+"";
- if(this.format == "JSON")
- {
- eval("this.attributes="+(this.value.substring(this.value.lastIndexOf("{"),this.value.lastIndexOf(";")))+";");
- }
- };
- Cookie.prototype.setValue = function (newValue, bContinue)
- {
- if(this.format == "STR")
- {
- this.value = (bContinue == false) ? newValue : this.value+newValue;
- Cookie.prototype.saveCookie();
- return true;
- }
- else
- {
- this.value = newValue;
- Cookie.prototype.saveCookie();
- return true;
- }
- };
- Cookie.prototype.setExpire = function (iExpire, sUnity)
- {
- var eArgv = this.setExpire.arguments;
- var eArgc = this.setExpire.arguments.length;
- if(eArgc >= 1 && sUnity != "until"){FoU = "for";}
- if(eArgc > 1 && sUnity == "until"){FoU = "until";}
- if(FoU == "for")
- {
- if(sUnity == "secondes" || sUnity == "s" || sUnity == undefined || sUnity == "sec")
- {
- date_exp.setTime(date_exp.getTime()+(iExpire));
- this.expiration = date_exp;
- }
- if(sUnity == "heures" || sUnity == "h" || sUnity == "hours")
- {
- date_exp.setTime(date_exp.getTime()+(iExpire*3600));
- this.expiration = date_exp;
- }
- if(sUnity == "jours" || sUnity == "j" || sUnity == "d" || sUnity == "days")
- {
- date_exp.setTime(date_exp.getTime()+(iExpire*3600*24));
- this.expiration = date_exp;
- }
- if(sUnity == "semaines" || sUnity == "sem" || sUnity == "weeks" || sUnity == "w")
- {
- date_exp.setTime(date_exp.getTime()+(iExpire*3600*24*7));
- this.expiration = date_exp;
- }
- if(sUnity == "mois" || sUnity == "m" || sUnity == "month")
- {
- date_exp.setTime(date_exp.getTime()+(iExpire*3600*24*30));
- this.expiration = date_exp;
- }
- if(sUnity == "annees" || sUnity == "a" || sUnity == "years" || sUnity == "y" || sUnity == "années")
- {
- date_exp.setTime(date_exp.getTime()+(iExpire*3600*24*365));
- this.expiration = date_exp;
- }
- }
- if(FoU == "until")
- {
- jour = iExpire.split(/\//)[0];
- mois = iExpire.split(/\//)[1];
- annee = iExpire.split(/\//)[2];
- timeStamp = ((parseInt(annee)-1970)*365*24*3600)+(parseInt(mois)*31*24*3600)+(parseInt(jour)*24*3600);
- date_exp.setTime(timeStamp);
- this.expiration = date_exp;
- }
- Cookie.prototype.saveCookie();
- };
- Cookie.prototype.cookieEnabled = function()
- {
- return navigator.cookieEnabled;
- };
- Cookie.prototype.removeCookie = function(name)
- {
- var exp = new Date();
- exp.setTime(exp.getTime() - 100000);
- var cValue = Cookie.prototype.getCookie(name);
- document.cookie = name+"="+cValue+"; expires="+exp.toGMTString();
- };
- Cookie.prototype.addAttribute = function(sAttribute, sValue)
- {
- if(this.format == "JSON")
- {
- this.value = this.value.substring(0, this.value.lastIndexOf("};"));
- this.value += ","+sAttribute+':"'+sValue+'"';
- this.value += "};";
- Cookie.prototype.saveCookie();
- return true;
- }
- else
- {
- return false;
- }
- };
- Cookie.prototype.resetCookie = function()
- {
- if(this.format == "STR")
- {
- this.value = "";
- }
- if(this.format == "JSON")
- {
- this.name+'={anonymousAttribute:""};';
- }
- Cookie.prototype.saveCookie();
- return true;
- };
- Cookie.prototype.deleteAttribute = function(sAttributeName)
- {
- if(this.format == "JSON")
- {
- eval(this.value)
- eval('sAttribute = '+this.name+'[sAttributeName];');
- var reg = new RegExp(','+sAttributeName+':"'+sAttribute+'"');
- this.value = this.value.replace(reg, "");
- Cookie.prototype.saveCookie();
- return true;
- }
- else
- {
- return false;
- }
- };
- Cookie.prototype.editAttribute = function(sAttributeName, sNewValue)
- {
- if(this.format == "JSON")
- {
- Cookie.prototype.deleteAttribute(sAttributeName);
- Cookie.prototype.addAttribute(sAttributeName, sNewValue);
- return true;
- }
- else
- {
- return false;
- }
- };
- Cookie.prototype.setFormat = function(sFormat)
- {
- if(sFormat == "STR" || Sformat == "JSON")
- {
- this.format = sFormat;
- return true;
- }
- else
- {
- return false;
- }
- };
-
- /* Exemple d'utilisation */
- cookie1 = new Cookie("cook1", "STR", "okay");
- alert(cookie1.value);
-
- cookie2 = new Cookie("cook2", "JSON")
- cookie2.addAttribute("cookie1", cookie2.getAttribute("cook1"));
- alert(cookie2.attributes.cookie1);
-
-
function Cookie(sName, sFormat, sValue)
{
var argc = Cookie.arguments.length;
/*attributes*/
if(sFormat != "GET" && sFormat != "get")
{
this.name = sName;
this.format = sFormat;
this.value = (argc > 2) ? (sValue) : ("");
date_exp = new Date();
date_exp.setTime(date_exp.getTime()+((argc > 2) ? (iExpiration) : (365*24*3600)));
this.expiration = date_exp;
if(this.format == "JSON"){this.value = this.name+'={anonymousAttribute:""};';}
if(argc > 1){this.saveCookie();}
}
if(sFormat == "GET" || sFormat == "get")
{
this.name = sName;
this.value = this.getCookie(sName);
date_exp = new Date();
date_exp.setTime(date_exp.getTime()+((argc > 2) ? (iExpiration) : (365*24*3600)));
this.expiration = date_exp;
this.format = (/=\{.+\};/i.test(this.value)==true) ? "JSON" : "STR";
}
}
/* Methodes */
Cookie.prototype.getCookieVal = function(offset)
{
var endstr=document.cookie.indexOf (";", offset);
if (endstr==-1)
endstr=document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
};
Cookie.prototype.getCookie = function (name)
{
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen)
{
var j=i+alen;
if (document.cookie.substring(i, j)==arg)
{
return Cookie.prototype.getCookieVal (j);
}
i=document.cookie.indexOf(" ",i)+1;
if (i==0){break;}
}
return null;
};
Cookie.prototype.saveCookie = function ()
{
var expires= this.expiration;
document.cookie=this.name+"="+escape(this.value)+((expires==null) ? "" : ("; expires="+expires.toGMTString()))+""+""+"";
if(this.format == "JSON")
{
eval("this.attributes="+(this.value.substring(this.value.lastIndexOf("{"),this.value.lastIndexOf(";")))+";");
}
};
Cookie.prototype.setValue = function (newValue, bContinue)
{
if(this.format == "STR")
{
this.value = (bContinue == false) ? newValue : this.value+newValue;
Cookie.prototype.saveCookie();
return true;
}
else
{
this.value = newValue;
Cookie.prototype.saveCookie();
return true;
}
};
Cookie.prototype.setExpire = function (iExpire, sUnity)
{
var eArgv = this.setExpire.arguments;
var eArgc = this.setExpire.arguments.length;
if(eArgc >= 1 && sUnity != "until"){FoU = "for";}
if(eArgc > 1 && sUnity == "until"){FoU = "until";}
if(FoU == "for")
{
if(sUnity == "secondes" || sUnity == "s" || sUnity == undefined || sUnity == "sec")
{
date_exp.setTime(date_exp.getTime()+(iExpire));
this.expiration = date_exp;
}
if(sUnity == "heures" || sUnity == "h" || sUnity == "hours")
{
date_exp.setTime(date_exp.getTime()+(iExpire*3600));
this.expiration = date_exp;
}
if(sUnity == "jours" || sUnity == "j" || sUnity == "d" || sUnity == "days")
{
date_exp.setTime(date_exp.getTime()+(iExpire*3600*24));
this.expiration = date_exp;
}
if(sUnity == "semaines" || sUnity == "sem" || sUnity == "weeks" || sUnity == "w")
{
date_exp.setTime(date_exp.getTime()+(iExpire*3600*24*7));
this.expiration = date_exp;
}
if(sUnity == "mois" || sUnity == "m" || sUnity == "month")
{
date_exp.setTime(date_exp.getTime()+(iExpire*3600*24*30));
this.expiration = date_exp;
}
if(sUnity == "annees" || sUnity == "a" || sUnity == "years" || sUnity == "y" || sUnity == "années")
{
date_exp.setTime(date_exp.getTime()+(iExpire*3600*24*365));
this.expiration = date_exp;
}
}
if(FoU == "until")
{
jour = iExpire.split(/\//)[0];
mois = iExpire.split(/\//)[1];
annee = iExpire.split(/\//)[2];
timeStamp = ((parseInt(annee)-1970)*365*24*3600)+(parseInt(mois)*31*24*3600)+(parseInt(jour)*24*3600);
date_exp.setTime(timeStamp);
this.expiration = date_exp;
}
Cookie.prototype.saveCookie();
};
Cookie.prototype.cookieEnabled = function()
{
return navigator.cookieEnabled;
};
Cookie.prototype.removeCookie = function(name)
{
var exp = new Date();
exp.setTime(exp.getTime() - 100000);
var cValue = Cookie.prototype.getCookie(name);
document.cookie = name+"="+cValue+"; expires="+exp.toGMTString();
};
Cookie.prototype.addAttribute = function(sAttribute, sValue)
{
if(this.format == "JSON")
{
this.value = this.value.substring(0, this.value.lastIndexOf("};"));
this.value += ","+sAttribute+':"'+sValue+'"';
this.value += "};";
Cookie.prototype.saveCookie();
return true;
}
else
{
return false;
}
};
Cookie.prototype.resetCookie = function()
{
if(this.format == "STR")
{
this.value = "";
}
if(this.format == "JSON")
{
this.name+'={anonymousAttribute:""};';
}
Cookie.prototype.saveCookie();
return true;
};
Cookie.prototype.deleteAttribute = function(sAttributeName)
{
if(this.format == "JSON")
{
eval(this.value)
eval('sAttribute = '+this.name+'[sAttributeName];');
var reg = new RegExp(','+sAttributeName+':"'+sAttribute+'"');
this.value = this.value.replace(reg, "");
Cookie.prototype.saveCookie();
return true;
}
else
{
return false;
}
};
Cookie.prototype.editAttribute = function(sAttributeName, sNewValue)
{
if(this.format == "JSON")
{
Cookie.prototype.deleteAttribute(sAttributeName);
Cookie.prototype.addAttribute(sAttributeName, sNewValue);
return true;
}
else
{
return false;
}
};
Cookie.prototype.setFormat = function(sFormat)
{
if(sFormat == "STR" || Sformat == "JSON")
{
this.format = sFormat;
return true;
}
else
{
return false;
}
};
/* Exemple d'utilisation */
cookie1 = new Cookie("cook1", "STR", "okay");
alert(cookie1.value);
cookie2 = new Cookie("cook2", "JSON")
cookie2.addAttribute("cookie1", cookie2.getAttribute("cook1"));
alert(cookie2.attributes.cookie1);
Conclusion
Méthodes et attributs de la class pour l'utilisateur: Méthodes: - setValue([string] sValue, [boleen] bContinue): Modifie la valeur du cookie, l'argument bContinue indique s'il on écrit à la suite du cookie ou si on efface tout pour réécrire par dessu
- saveCookie(): Sauvegarde votre cookie, cette méthode est appelée à chaque fois que une modification est apportée
- setExpire([string] sExpire, [string] sUnity): Modifie le délai du cookie, la chaine de caractères sExpire est la valeur et sUnity est l'unitée utilisée (secondes, jour, mois) - getCookie(name): retourne la valeur du cookie voulu
- removeCookie(name): efface un cookie.
- resetCookie(): reinitialise le cookie sans qu'il perde son format, utile au format JSON sinon il suffit de réinitialiser la value.
- addAttribute(sAttribute, sValue): (dans un cookie au format JSON), ajoute un attribut au cookie
- deleteAttribute(sAttributeName): suprime l'attribut dont le nom est passé en argument
- editAttribute(sAttributeName, sNewValue) modifie la valeur de l'attribut dont le nom est passé en argument
- setFormat(sFormat): configure le format. retourne false si le format passé en argument est erroné
Attributs: name: nom du cookie value: valeur du cookie format: format du cookie /!\ changer avec précotion attributes: Sous objet contenant les attributs du cookie (ex: attributes.anonumousAttribute) /!\ immodifiable, juste pour info
/!\ Attention si vous modifiez ces valeur sans passer par des accesseur (methodes) utiliser la methode saveCookie() pour sauvegarder.
/!\ NE vous préocuper des autres méthodes, sauf si vous voulez améliorer ce code.
Historique
- 07 novembre 2009 21:02:50 :
- J'ai ajouter la méthode removeCookie() et j'ai modifier la méthode setExpire()
- 08 novembre 2009 18:07:12 :
- Possibilité de créer des cookies au format JSON
- 08 novembre 2009 18:23:44 :
- ajout des methodes en conclusion
- 13 novembre 2009 18:14:54 :
- ==>
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Object() [ par revolt ]
Bonjour, voici mon pb : On m'a donné un fichier ecrit en javascript qui utilise un objet appelé API_78Ce fichier apelle des fonction que je
Design pattern pour une factory [ par kankrelune ]
Bonjour...Je suis en train de finir un code poo en javascript et je bloque sur un truc... je voudrais donc votre avis d'autant plus que javascript n'e
Problème avec les propriétés d'un objet [ par wuconceptor ]
Alors voilà, j'ai une liste (SELECT) et quand je choisis une option j'aimerais que ça me change la "visibility" de l'objet qui porte l
[balise object] modifier dynamiquement un object [ par glanumf ]
Bonjour a tous, J'arive pas a modifier une balise object de mon document HTML. Bon j'explique plus precisemment, j'ai mit un object dans ma page a
loadXML et Firefox [ par epoc ]
j'instancie un objet xml de cette manière pour firefox : document.implementation.createDocument("", "", null) j'aimerais pouvoir faire un loadXML
Chat Box PHP/Javascript/Html/Cookie ect... [ par zlitus ]
Salut. Je suis en train de programmer un petit chat pour mon site. seulement j'ai un probleme, j'aimerai que le visiteur marque son pseudo au dé
Objet TDC activeX , recuperation valuer DATAFLD pour la placer dans une variable JavaScript [ par hambis ]
Bonjour a tous Si vous pouvez m aider au problème suivant : J utilise l objet TDC Active X (I.Expl.) pour afficher une liste d articles contenu dans u
AJAX, le status de mon objet est toujours égal à "0", please help me ! [ par romtrico064649 ]
Bonjour,Je désire effectuer une request de type XMLHTTPRequest sur un fichier XML.Voici mon soucis, je m'explique :Le code ci dessous contient deux fo
Liste liée - Formulaire [ par onylink ]
Bonjour, J'essai de liées des listes dans un formulaire, mais après mon choix rien ne se passe.. Mais je n'ai pas d'erreur.. Page appelante :<pre clas
object pdf cliquable? [ par couney21 ]
Bonjours, Je voudrais rendre un PDF charger par html Réac
|
Derniers Blogs
CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT)CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT) par FREMYCOMPANY
Bonjour à tous, Je viens de publier une proposition comprenant 5 pseudo-classes pour le CSS Working Group ayant trait à l'état de chargement d'un élément (ex: IMG,VIDEO,AUDIO,OBJECT pour l'HTML.). Si le c½ur vous en dit, vous pouvez retrouver cette p...
Cliquez pour lire la suite de l'article par FREMYCOMPANY MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ?MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ? par ROMELARD Fabrice
Formation initiale Durant la formation, le découpage classique est le suivant (je donnerai les équivalences Suisse lorsque je les connaîtrais) : Ecole primaire jusqu'au Collège : Formation générale permettant d'obtenir les méthodes...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice Y'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENTY'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENT par Aleks
Quand on a ce genre d'erreur sans log :
Et bas on a juste envie de choper le gas de Microsoft qu'a développé ça et lui foutre des baffes de Coboye ! ...
Cliquez pour lire la suite de l'article par Aleks [HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL[HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL par Pierrick CATRO-BROUILLET
Avec la sortie prochaine de la Beta Consumer Preview de Windows 8, j'avais envie de revenir sur une des fonctionnalités que j'attends le plus et que, en bon geek que je suis, j'utilise déjà : Hyper-V 3 ainsi son module PowerShell.
Il y a déjà pléthor...
Cliquez pour lire la suite de l'article par Pierrick CATRO-BROUILLET IIS7 - COMPRESSION GZIPIIS7 - COMPRESSION GZIP par cyril
La compression GZIP permet d'améliorer les performances de navigation en compressant ce qu'envoie le serveur à un client. Pour comprendre comment cela fonctionne, regardons ce qu'il se passe au niveau HTTP lorsqu'un client tente d'accéder à une ress...
Cliquez pour lire la suite de l'article par cyril
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|