cookies.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var utils = require('./../utils');
  3. module.exports = (
  4. utils.isStandardBrowserEnv() ?
  5. // Standard browser envs support document.cookie
  6. (function standardBrowserEnv() {
  7. return {
  8. write: function write(name, value, expires, path, domain, secure) {
  9. var cookie = [];
  10. cookie.push(name + '=' + encodeURIComponent(value));
  11. if (utils.isNumber(expires)) {
  12. cookie.push('expires=' + new Date(expires).toGMTString());
  13. }
  14. if (utils.isString(path)) {
  15. cookie.push('path=' + path);
  16. }
  17. if (utils.isString(domain)) {
  18. cookie.push('domain=' + domain);
  19. }
  20. if (secure === true) {
  21. cookie.push('secure');
  22. }
  23. document.cookie = cookie.join('; ');
  24. },
  25. read: function read(name) {
  26. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  27. return (match ? decodeURIComponent(match[3]) : null);
  28. },
  29. remove: function remove(name) {
  30. this.write(name, '', Date.now() - 86400000);
  31. }
  32. };
  33. })() :
  34. // Non standard browser env (web workers, react-native) lack needed support.
  35. (function nonStandardBrowserEnv() {
  36. return {
  37. write: function write() {},
  38. read: function read() { return null; },
  39. remove: function remove() {}
  40. };
  41. })()
  42. );