Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

WebDriver Wait For Ajax Completion

Nowadays, most web applications use Ajax Call to retrieve data from the server. When using Selenium WebDriver, WebDriver needs to dynamically wait for Ajax call completion, so that the webpage under test is fully rendered when Ajax call is ended. This code below makes WebDriver wait until Ajax Call is over within the time out period that is defined in the App.Config file of the test application.

 

 

Code Snippet
  1. public void WaitForAjaxCompletion()
  2.         {
  3.             Stopwatch sw = new Stopwatch();
  4.             sw.Start();
  5.             try
  6.             {
  7.                 while (sw.Elapsed.TotalSeconds < int.Parse(ConfigurationManager.AppSettings["TimeOut"]))
  8.                 {
  9.                     var ajaxIsComplete = (bool)((IJavaScriptExecutor)_webDriver).ExecuteScript("return window.jQuery != undefined && jQuery.active==0");
  10.                     if (ajaxIsComplete)
  11.                         break;
  12.                     Thread.Sleep(100);
  13.                 }
  14.             }
  15.             catch (Exception)
  16.             {
  17.                 Console.WriteLine("Ajax call time out time {0} has passed ", ConfigurationManager.AppSettings["TimeOut"].ToString());
  18.             }
  19.             finally
  20.             {
  21.                 sw.Stop();
  22.             }
  23.         }