cookie.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. export function getCookie(name: string): string {
  2. let arr: RegExpMatchArray | null;
  3. const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
  4. if ((arr = document.cookie.match(reg))) {
  5. return decodeURIComponent(arr[2]);
  6. } else {
  7. return '';
  8. }
  9. }
  10. // options: {
  11. // expires?:number,
  12. // path?:string,
  13. // domain?:string
  14. // }
  15. export function setCookie(name: string, value: string, options?: any) {
  16. const myWindow: any = window;
  17. let cookieStr = myWindow.escape(name) + '=' + myWindow.escape(value) + ';';
  18. if (!options) {
  19. options = {};
  20. }
  21. if (options.expires) {
  22. const dtExpires = new Date(new Date().getTime() + options.expires * 1000 * 60 * 60 * 24);
  23. cookieStr += 'expires=' + dtExpires.toUTCString() + ';';
  24. }
  25. if (options.path) {
  26. cookieStr += 'path=' + options.path + ';';
  27. }
  28. if (options.domain) {
  29. cookieStr += 'domain=' + options.domain + ';';
  30. }
  31. document.cookie = cookieStr;
  32. }
  33. // options: {
  34. // path?:string,
  35. // domain?:string
  36. // }
  37. export function deleteCookie(name: string, options?: any) {
  38. if (getCookie(name)) {
  39. if (!options) {
  40. options = {};
  41. }
  42. options.expires = -1;
  43. setCookie(name, '', options);
  44. }
  45. }