BrowserExtensions.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using CefGlue.Tests.CustomSchemes;
  2. using System;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using Xilium.CefGlue.Avalonia;
  6. using Xilium.CefGlue.Common.Events;
  7. namespace CefGlue.Tests
  8. {
  9. public static class BrowserExtensions
  10. {
  11. public static Task LoadContent(this AvaloniaCefBrowser browser, string content)
  12. {
  13. var loadTask = browser.AwaitLoad();
  14. var url = "data:text/html;charset=utf-8;base64," + Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(content));
  15. browser.Address = url;
  16. return loadTask;
  17. }
  18. public static Task AwaitLoad(this AvaloniaCefBrowser browser)
  19. {
  20. var taskCompletionSource = new TaskCompletionSource<bool>();
  21. void UnsubcribeEvents()
  22. {
  23. browser.LoadEnd -= OnBrowserLoadEnd;
  24. browser.LoadError -= OnBrowserLoadError;
  25. }
  26. void OnBrowserLoadError(object sender, LoadErrorEventArgs e)
  27. {
  28. UnsubcribeEvents();
  29. taskCompletionSource.SetException(new Exception(e.ErrorText));
  30. }
  31. void OnBrowserLoadEnd(object sender, LoadEndEventArgs e)
  32. {
  33. if (e.Frame.Url.StartsWith("data:") || e.Frame.Url.StartsWith(CustomSchemeHandlerFactory.SchemeName + ":"))
  34. {
  35. UnsubcribeEvents();
  36. taskCompletionSource.SetResult(true);
  37. }
  38. }
  39. browser.LoadEnd += OnBrowserLoadEnd;
  40. browser.LoadError += OnBrowserLoadError;
  41. return taskCompletionSource.Task;
  42. }
  43. }
  44. }