dom/cookies.js

  1. /**
  2. * @fileoverview Cookies utility methods.
  3. *
  4. * @see https://google.github.io/styleguide/javascriptguide.xml
  5. * @see https://developers.google.com/closure/compiler/docs/js-for-compiler
  6. * @module glize/dom/cookies
  7. * @requires glize/utils/number
  8. */
  9. import { uint32 } from '../utils/number.js';
  10. /**
  11. * Sets a cookie.
  12. * @param {string} key The name of the cookie.
  13. * @param {string} value The value of the cookie.
  14. * @param {number} expiration The days after the cookie expires.
  15. * @param {string=} opt_domain Optional, domain that the cookie belongs to.
  16. * @method
  17. */
  18. export const set = (key, value, expiration, opt_domain) => {
  19. const expires = new Date(expiration * 864E5 + Date.now()).toGMTString();
  20. document.cookie = escape(key) + '=' + escape(value || '') +
  21. '; expires=' + expires +
  22. '; path=/; domain=' + (opt_domain || document.domain);
  23. };
  24. /**
  25. * Gets the value for the first cookie with the given name.
  26. * @param {string} key The name of the cookie to get.
  27. * @param {string=} opt_default The optional default value.
  28. * @return {string} The value of the cookie. If no cookie is set this
  29. * returns opt_default or undefined if opt_default is not provided.
  30. * @method
  31. */
  32. export const get = (key, opt_default = '') => {
  33. const re = key + '=([^;].+?)(;|$)';
  34. return unescape((document.cookie.match(re) || [])[1] || opt_default);
  35. };
  36. /**
  37. * Removes and expires a cookie.
  38. * @param {string} key The cookie name.
  39. * @return {boolean} Whether the cookie existed before it was removed.
  40. * @method
  41. */
  42. export const remove = (key) => {
  43. const value = get(key);
  44. set(key, '', 0);
  45. return !!value;
  46. };
  47. /**
  48. * Removes and expires all cookie.
  49. * @method
  50. */
  51. export const clear = () => {
  52. const names = keys();
  53. let length = uint32(names.length);
  54. while (length--) {
  55. remove(names[length]);
  56. }
  57. };
  58. /**
  59. * Gets list of stored keys.
  60. * @return {!Array<string>} Returns list of stored keys.
  61. * @method
  62. */
  63. export const keys = () => {
  64. const re = /;\s*/;
  65. const parts = document.cookie.split(re);
  66. let length = uint32(parts.length);
  67. const keys = new Array(length - 1);
  68. while (length--) {
  69. keys[length] = (parts[length].split('=')[0]);
  70. }
  71. return keys;
  72. };