cookies.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import utils from '../utils.js';
  2. import platform from '../platform/index.js';
  3. export default platform.hasStandardBrowserEnv
  4. ? // Standard browser envs support document.cookie
  5. {
  6. write(name, value, expires, path, domain, secure, sameSite) {
  7. if (typeof document === 'undefined') return;
  8. const cookie = [`${name}=${encodeURIComponent(value)}`];
  9. if (utils.isNumber(expires)) {
  10. cookie.push(`expires=${new Date(expires).toUTCString()}`);
  11. }
  12. if (utils.isString(path)) {
  13. cookie.push(`path=${path}`);
  14. }
  15. if (utils.isString(domain)) {
  16. cookie.push(`domain=${domain}`);
  17. }
  18. if (secure === true) {
  19. cookie.push('secure');
  20. }
  21. if (utils.isString(sameSite)) {
  22. cookie.push(`SameSite=${sameSite}`);
  23. }
  24. document.cookie = cookie.join('; ');
  25. },
  26. read(name) {
  27. if (typeof document === 'undefined') return null;
  28. const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
  29. return match ? decodeURIComponent(match[1]) : null;
  30. },
  31. remove(name) {
  32. this.write(name, '', Date.now() - 86400000, '/');
  33. },
  34. }
  35. : // Non-standard browser env (web workers, react-native) lack needed support.
  36. {
  37. write() {},
  38. read() {
  39. return null;
  40. },
  41. remove() {},
  42. };