Skip to content

Instantly share code, notes, and snippets.

@jamc92
Created February 22, 2015 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamc92/dfd1a763dfb0607799b7 to your computer and use it in GitHub Desktop.
Save jamc92/dfd1a763dfb0607799b7 to your computer and use it in GitHub Desktop.
JS - Cookies
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Cookies en JS</title>
</head>
<script>
<!--// Creando coockie en javascript-->
document.cookie = "username=Mario; expires=Mon, 2 Feb 2015 11:30:00 UTC";
<!-- Para eliminar una fecha de expiración se le coloca una fecha vieja(pasada)-->
document.cookie = "username=; expires=Mon, 01 Jan 00:00:00 UTC";
<!-- Gestion de cookies -->
function createCookie(clave, valor, expiracion) {
var d = new Date();
d.setTime(d.getTime()) + (expiracion * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.coocke = clave + "=" + valor + "; " + expires;
}
<!-- Obtener una cookie -->
function getCookie(key) {
var name = key + "=";
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) == 0) return c.substring(name.length, c.length);
}
return "";
}
<!--Comprobar si una cookie ha sido creada-->
function getCookie(key) {
var key = getCookie(key)
if (key != "") {
console.log("La cookie existe);
} else {
console.log("La cookie no existe");
}
}
</script>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment