Forum Discussion

azakharov's avatar
azakharov
Contributor
11 years ago
Solved

Waiting for XPath or CSS elements

Hi,



What is the best strategy for waiting XPath and CSS elements to be displayed on a page?



They are AJAX generated so I can't rely on page.Wait().



I need to achieve the following (JScript):



var element = page.QuerySelector("input[name='Name']");

// pseudo code: element - wait for element to be loaded and displayed on a page;

element.SetText('Text");



I don't want to use hardcoded "aqUtils.Delay(5000);" since it's not good and reliable practice.



Thanks a lot!

  • I usually do a code loop until the object is found or until some sort of safety timeout period is exceeded.  I write in VBScript, but hopefully, you can see the intention and create something similar to suit your needs.




     



     'We'll wait for ten seconds


    curTime = aqDateTime.Now


    endTime = aqDateTime.AddSeconds(curTime, 10)




    'Start loop


    Do  



    'Optional delay to space out the attempts to find the element


    aqUtils.Delay 250



    ' QuerySelector will return object or Nothing/null

    Set elementOb = Page.QuerySelector("whatever")

     


    Loop Until Not elementOb Is Nothing Or aqDateTime.Compare(aqDateTime.Now, endTime) > -1

    ' Loops exits if the elementOb is a valid object (not Nothing) or we've passed the set end time



    If elementOb Is Nothing Then Log.Error "Failed to find element object."


     


    End Sub

2 Replies

  • Thanks a lot Gratis!



    I ended up adding my own function but I wonder if there is something built in.



    Here's what I did (JScript):




    function Wait_For_Element(element, timeout)


    {


      var timer = 0 


      while (element === null  && timer < timeout)


      {


        aqUtils.Delay(500);


     timer += 500;


     element;


      }


    }



    Wait_For_Element(css/xpath selector, 10000);

  • rgratis's avatar
    rgratis
    Frequent Contributor

    I usually do a code loop until the object is found or until some sort of safety timeout period is exceeded.  I write in VBScript, but hopefully, you can see the intention and create something similar to suit your needs.




     



     'We'll wait for ten seconds


    curTime = aqDateTime.Now


    endTime = aqDateTime.AddSeconds(curTime, 10)




    'Start loop


    Do  



    'Optional delay to space out the attempts to find the element


    aqUtils.Delay 250



    ' QuerySelector will return object or Nothing/null

    Set elementOb = Page.QuerySelector("whatever")

     


    Loop Until Not elementOb Is Nothing Or aqDateTime.Compare(aqDateTime.Now, endTime) > -1

    ' Loops exits if the elementOb is a valid object (not Nothing) or we've passed the set end time



    If elementOb Is Nothing Then Log.Error "Failed to find element object."


     


    End Sub