Languages
[Edit]
EN

JavaScript - get / set / remove cookies (custom solution)

7 points
Created by:
Aisha
418

In this short article we would like to show how to get, set and remove cookies in JavaScript in web browser usiong custom light cookies manager implementation.

By default cookies usage with built-in web browser API is not intuitive. In practice we are able to wite own one cookies manager what is presented in this article.

The example presented in the article was created to store cookies in safe way - escaping dangerous characters with encodeURIComponent() function, that can be changed to some other if it is needed.

The below manager provides API to:

  • check if cookies are enabled
  • get string, boolean, number and date value cookies
  • set string, boolean, number and date value cookies,
  • remove cookie,
  • calculate expiration time from: seconds, minutes, hours and days.
Set and get cookies with JavaScript in web browser.
Set and get cookies with JavaScript in web browser.

Usage example:

Full API:

Cookies.checkCookiesEnabled()

Cookies.removeCookieValue(name)

Cookies.getStringCookie(name)

Cookies.setStringCookie(name, value, expiration, domain, path)

Cookies.getBooleanCookie(name)

Cookies.setBooleanCookie(name, value, expiration, domain, path)

Cookies.getNumberCookie(name)

Cookies.setNumberCookie(name, value, expiration, domain, path)

Cookies.getDateCookie(name)

Cookies.setDateCookie(name, value, expiration, domain, path)

Cookies.calculateExpirationSeconds(seconds)

Cookies.calculateExpirationMinutes(minutes)

Cookies.calculateExpirationHours(hours)

Cookies.calculateExpirationDays(days)

Where:

  • expiration, domain and path are optional,
  • calculatExpiration... functions return time when cookie will expire.

 

Manager implementation

Edit

 

Alternative titles

  1. JavaScript - custom cookies manager
  2. JavaScript - own cookies manager
  3. JavaScript - get / set / remove cookies (own logic)
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join