Guest User

Untitled

a guest
Jul 23rd, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. public static class WebBrowerExtension
  2. {
  3. /// <summary>
  4. /// 监听某个条件满足后(如UI元素渲染完毕)执行指定操作(多线程)
  5. /// </summary>
  6. /// <param name="condition">待满足条件(UI资源需满足跨线程访问)</param>
  7. /// <param name="operation">待执行操作((UI资源需满足跨线程访问))</param>
  8. /// <param name="timeOut">等待条件满足的超时时间</param>
  9. public static void WaitUtil(this WebBrowser brower, Predicate<WebBrowser> condition, Action<WebBrowser> operation, TimeSpan timeOut)
  10. {
  11. new Thread(() =>
  12. {
  13. Stopwatch watch = new Stopwatch();
  14. watch.Start();
  15. while (true)
  16. {
  17. //超时
  18. if (watch.Elapsed.TotalMilliseconds > timeOut.TotalMilliseconds)
  19. {
  20. watch.Stop();
  21. break;
  22. }
  23.  
  24. if (condition(brower))
  25. {
  26. operation(brower);
  27. watch.Stop();
  28. break;
  29. }
  30. Thread.Sleep(1000);
  31. }
  32. })
  33. { IsBackground = true }.Start();
  34. }
  35.  
  36.  
  37. /// <summary>
  38. /// 执行附加脚本
  39. /// </summary>
  40. /// <param name="browser">浏览器对象</param>
  41. /// <param name="script">待执行脚本</param>
  42. /// <param name="canBeCleared">脚本内容是否可以被清除(定时任务应设置为false)</param>
  43. public static void ExecuteScript(this WebBrowser browser, string script, bool canBeCleared = true)
  44. {
  45. var body = browser.Document.GetElementsByTagName("body")[0];
  46. var newScript = browser.Document.CreateElement("script");
  47. newScript.SetAttribute("canBeCleared", "true");
  48. newScript.InnerHtml = $"(function(){{$('[canBeCleared=true]').remove();{script}}})();";
  49. body.AppendChild(newScript);
  50. }
  51. }
Add Comment
Please, Sign In to add comment