Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

cookie-handler.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. module.exports = function init(storage, ToughCookie, WebStorageCookieStore) {
  2. var storeKey = '__advancedHttpCookieStore__';
  3. var store = new WebStorageCookieStore(storage, storeKey);
  4. var cookieJar = new ToughCookie.CookieJar(store);
  5. return {
  6. setCookieFromString: setCookieFromString,
  7. setCookie: setCookie,
  8. getCookieString: getCookieString,
  9. clearCookies: clearCookies,
  10. removeCookies: removeCookies
  11. };
  12. function splitCookieString(cookieStr) {
  13. var cookieParts = cookieStr.split(',');
  14. var splitCookies = [];
  15. var processedCookie = null;
  16. for (var i = 0; i < cookieParts.length; ++i) {
  17. if (cookieParts[i].substr(-11, 8).toLowerCase() === 'expires=') {
  18. processedCookie = cookieParts[i] + ',' + cookieParts[i + 1];
  19. i++;
  20. } else {
  21. processedCookie = cookieParts[i];
  22. }
  23. processedCookie = processedCookie.trim();
  24. splitCookies.push(processedCookie);
  25. }
  26. return splitCookies;
  27. }
  28. function setCookieFromString(url, cookieStr) {
  29. if (!cookieStr) return;
  30. var cookies = splitCookieString(cookieStr);
  31. for (var i = 0; i < cookies.length; ++i) {
  32. cookieJar.setCookieSync(cookies[i], url, { ignoreError: true });
  33. }
  34. }
  35. function setCookie(url, cookie, options) {
  36. options = options || {};
  37. options.ignoreError = false;
  38. cookieJar.setCookieSync(cookie, url, options);
  39. }
  40. function getCookieString(url) {
  41. return cookieJar.getCookieStringSync(url);
  42. }
  43. function clearCookies() {
  44. window.localStorage.removeItem(storeKey);
  45. }
  46. function removeCookies(url, cb) {
  47. cookieJar.getCookies(url, function (error, cookies) {
  48. if (!cookies || cookies.length === 0) {
  49. return cb(null, []);
  50. }
  51. var domain = cookies[0].domain;
  52. cookieJar.store.removeCookies(domain, null, cb);
  53. });
  54. }
  55. };