Browser - Cookie

> (World Wide) Web - (W3|WWW) > Web - Browser

1 - About

HTTP cookies management in the client side (browser) via javascript.

document.cookie is a property of the browser document that returns the HTTP cookies that apply to the Document. If there are no cookies or cookies can't be applied to this resource, the empty string will be returned.

With the Web API and Document cookie property

Advertising

3 - Management

3.1 - HttpOnly

A cookie set with the HttpOnly flag, tells the browser that it cannot access this cookie (ie the cookie should only be managed by the server)

3.2 - Set

Set two cookies

document.cookie = "name=nico";
document.cookie = "favorite_color=blue";

3.3 - Get

3.3.1 - All

  • Read the cookies. The cookies are in a string separated with a ;

console.log("All the cookies:");
console.log(document.cookie);

For the value of the google analytics cookie, see Google Analytics - Utma Cookie

3.3.2 - Filter

  • Only the cookie that start with a underscore

console.log("All the cookies:");
console.log(document.cookie.split(";").filter( (item) => item.trim().startsWith('_') ));

Advertising

3.3.3 - by name

There is no function in the Javascript Web API to get a cookie by name.

We need to parse the value of document.cookie. This is a string of all cookies in a key pair format separated by a ;

  • Setting a cookie
cookie_key = "name";
document.cookie = cookie_key+"=nico";
  • Regular expression method. Because the key value is saved in variable, we cannot create a regular expression pattern as a string and need to use a regexp constructor
regexp = new RegExp("(?:(?:^|.*;\\s*)"+cookie_key+"\\s*\\=\\s*([^;]*).*$)|^.*$");
var cookieValue = document.cookie.replace(regexp, "$1");
console.log("Regular expression    : The value of the cookie with the name key is ("+cookieValue+")");
var cookieValue = document.cookie
    .split(";")
    .filter( (item) => item.trim().startsWith(cookie_key) )[0]
    .split("=")[1];
console.log("Functional Programming: The value of the cookie with the name key is ("+cookieValue+")");
  • Result

3.4 - Delete

document.cookie = "key=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

4 - Library

Advertising