cookies.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. :
  36. // Non-standard browser env (web workers, react-native) lack needed support.
  37. {
  38. write() {},
  39. read() {
  40. return null;
  41. },
  42. remove() {}
  43. };