cookies.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // Match name=value by splitting on the semicolon separator instead of building a
  29. // RegExp from `name` — interpolating an unescaped string into a RegExp would let
  30. // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
  31. // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
  32. // "; ", so ignore optional whitespace before each cookie name.
  33. const cookies = document.cookie.split(';');
  34. for (let i = 0; i < cookies.length; i++) {
  35. const cookie = cookies[i].replace(/^\s+/, '');
  36. const eq = cookie.indexOf('=');
  37. if (eq !== -1 && cookie.slice(0, eq) === name) {
  38. return decodeURIComponent(cookie.slice(eq + 1));
  39. }
  40. }
  41. return null;
  42. },
  43. remove(name) {
  44. this.write(name, '', Date.now() - 86400000, '/');
  45. },
  46. }
  47. : // Non-standard browser env (web workers, react-native) lack needed support.
  48. {
  49. write() {},
  50. read() {
  51. return null;
  52. },
  53. remove() {},
  54. };