CookieManager.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using UnityEngine;
  5. namespace ZenFulcrum.EmbeddedBrowser {
  6. public class CookieManager {
  7. internal readonly Browser browser;
  8. public CookieManager(Browser browser) {
  9. this.browser = browser;
  10. }
  11. //Keep the trampoline memory alive until the promise is resolved.
  12. private static readonly Dictionary<IPromise<List<Cookie>>, BrowserNative.GetCookieFunc> cookieFuncs = new Dictionary<IPromise<List<Cookie>>, BrowserNative.GetCookieFunc>();
  13. /**
  14. * Returns a list of all cookies in the browser across all domains.
  15. *
  16. * Note that cookies are shared between browser instances.
  17. *
  18. * If the browser is not ready yet (browser.IsReady or WhenReady()) this will return an empty list.
  19. */
  20. public IPromise<List<Cookie>> GetCookies() {
  21. Cookie.Init();
  22. var ret = new List<Cookie>();
  23. if (!browser.IsReady || !browser.enabled) return Promise<List<Cookie>>.Resolved(ret);
  24. var promise = new Promise<List<Cookie>>();
  25. BrowserNative.GetCookieFunc cookieFunc = cookie => {
  26. try {
  27. if (cookie == null) {
  28. browser.RunOnMainThread(() => promise.Resolve(ret));
  29. cookieFuncs.Remove(promise);
  30. return;
  31. }
  32. ret.Add(new Cookie(this, cookie));
  33. } catch (Exception ex) {
  34. Debug.LogException(ex);
  35. }
  36. };
  37. BrowserNative.zfb_getCookies(browser.browserId, cookieFunc);
  38. cookieFuncs[promise] = cookieFunc;
  39. return promise;
  40. }
  41. /**
  42. * Deletes all cookies in the browser.
  43. */
  44. public void ClearAll() {
  45. if (browser.DeferUnready(ClearAll)) return;
  46. BrowserNative.zfb_clearCookies(browser.browserId);
  47. }
  48. }
  49. }