I have a web program to analyze with selenium s/w. There’s lots of Javascript working on page-load.
This JavaScript code isn’t so nicely written but I can not alter something. Therefore looking forward to a feature to appear in the DOM with findElement() procedure isn’t a choice.

I would like to generate a common function in Java to await a site to fill, a potential alternative might be :

Operate a JavaScript software type WebDriver and store the effect of document.body.innerHTML in a chain variant physique.
Evaluate the human body variant to the previous edition of human anatomy. if they can be the same afterward establish increase a counter-top notChangedCount otherwise establish notChangedCount to no.
wait to get a little time (50 ms as an example).
if the site hasn’t changed for quite a while (500 ms like) therefore notChangedCount “>>= 10 then exit the trap otherwise cycle to step one.
Would you believe it is a legitimate option ?

If anybody really understood a common and constantly-appropriate solution, it might happen to be applied everywhere years past and might make our lives THEREFORE simpler.

You can find several steps you can take, but every one of them h-AS a difficulty:

As Ashwin Prabhu stated, once you learn the software nicely, it is possible to find it really is behavior and monitor some of it really is variants on windowpane or file etc. This option, nevertheless, isn’t for everybody else and can be utilized exclusively by you and just on a small established of web pages.
Your solution by finding the Html-code and whether it h-AS or was not altered for some moment is not bad (additionally, there exists a strategy to get the first and not modified HTML straight by WebDriver), but:
It requires quite a while to really maintain a site and can prolongate the evaluation considerably.
You never understand what the correct time is. The software may possibly be installing something huge that requires over 500 ms. There are several programs on our firm’s inner site that t-AKE a few seconds in MICROSOFT INTERNET EXPLORER. Your computer may be briefly short on assets – state an anti-virus will make your processor operate completely, then 500 Microsoft might be too-short actually for a complicated program.
Some scripts will never be completed. They call themselves with some delay (setTimeout()) and perform over and over and can potentially alter the HTML every moment they operate. Significantly, every “Internet 2.0” site does it. Actually Stack Over Flow. You can over-write the many typical approaches employed and look at the scripts using them as finished, but … you can not be sure.
What will happen if the software does something additional than altering the Hypertext Markup Language? It can do hundreds of stuff, maybe not only some innerHTML pleasure.
You’ll find tools to enable you to on this. Specifically this as well as this and others. The browser assistance because of this, nevertheless, is terrible. Opera started to make an effort to aid it from entirely FF4 onwards (still-evolving), MICROSOFT INTERNET EXPLORER h-AS fundamental help in IE9.
And that I think I can come up with yet another defective remedy shortly. The fact is – there is no clear answer on when to say “today the site is whole” due to the ever-lasting programs do-ing their perform. Decide one that serves you most readily useful, but watch out for its short-coming.

Within my case I ought to wait for a jquery plug-in performance in some component.. Especially “q-tip”

Centered in your tip, it labored flawlessly for me :

wait.until( new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript(“return document.readyState”).equals(“complete”);
}
}
);

You must wait for Javascript and jQuery to complete load. Run Javascript to verify if jQuery.active is 0 and document.readyState is whole, which implies the JS and jQuery fill is complete.

public boolean waitForJStoLoad() {

WebDriverWait wait = new WebDriverWait(driver, 30);

// wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return ((Long)executeJavaScript(“return jQuery.active”) == 0);
}
catch (Exception e) {
return true;
}
}
};

// wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return executeJavaScript(“return document.readyState”)
.toString().equals(“complete”);
}
};

return wait.until(jQueryLoad) && wait.until(jsLoad);
}

Does the JScatalog determine/initialize any famous variant on the windowpane?

If s O you might wait for the variant to look. It’s possible for you to use

((JavascriptExecutor)motorist).executeScript(Chain software, Item… args)

to analyze because of this state (some thing like: window. SomeClass && window. SomeClass.variant != Zero) and reunite a boolean true / untrue.

Place this in a WebDriverWait, and wait before the software earnings true.

To get it done correctly, you should manage the conditions.

Here is really how I do a delay for an I frame. This involves that your JUnit test group move the case of RemoteWebDriver into the site item :

public class IFrame1 extends LoadableComponent<IFrame1> {

private RemoteWebDriver driver;

@FindBy(id = “iFrame1TextFieldTestInputControlID” )
public WebElement iFrame1TextFieldInput;

@FindBy(id = “iFrame1TextFieldTestProcessButtonID” )
public WebElement copyButton;

public IFrame1( RemoteWebDriver drv ) {
super();
this.driver = drv;
this.driver.switchTo().defaultContent();
waitTimer(1, 1000);
this.driver.switchTo().frame(“BodyFrame1”);
LOGGER.info(“IFrame1 constructor…”);
}

@Override
protected void isLoaded() throws Error {
LOGGER.info(“IFrame1.isLoaded()…”);
PageFactory.initElements( driver, this );
try {
assertTrue( “Page visible title is not yet available.”, driver
.findElementByCssSelector(“body form#webDriverUnitiFrame1TestFormID h1”)
.getText().equals(“iFrame1 Test”) );
} catch ( NoSuchElementException e) {
LOGGER.info(“No such element.” );
assertTrue(“No such element.”, false);
}
}

@Override
protected void load() {
LOGGER.info(“IFrame1.load()…”);
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring( NoSuchElementException.class )
.ignoring( StaleElementReferenceException.class ) ;
wait.until( ExpectedConditions.presenceOfElementLocated(
By.cssSelector(“body form#webDriverUnitiFrame1TestFormID h1”) ) );
}
….

It’s possible for you to compose some sense to manage this. I ‘ve written an approach that can get back the WebElement which technique may be called 3 x or it is possible to raise time and a-DD a zero look for WebElement Listed Here Is an example

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.crowdanalytix.com/#home”);
WebElement webElement = getWebElement(driver, “homekkkkkkkkkkkk”);
int i = 1;
while (webElement == null && i < 4) {
webElement = getWebElement(driver, “homessssssssssss”);
System.out.println(“calling”);
i++;
}
System.out.println(webElement.getTagName());
System.out.println(“End”);
driver.close();
}

public static WebElement getWebElement(WebDriver driver, String id) {
WebElement myDynamicElement = null;
try {
myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By
.id(id)));
return myDynamicElement;
} catch (TimeoutException ex) {
return null;
}
}

Here’s from my own, personal signal:

Window.setTimeout runs only once a browser is nonproductive.
S O phoning the perform recursively (42 occasions) may take 100ms if there isn’t any action in the browser plus much more in case the browser is busy performing something different.

ExpectedCondition<Boolean> javascriptDone = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
try{//window.setTimeout executes only when browser is idle,
//introduces needed wait time when javascript is running in browser
return ((Boolean) ((JavascriptExecutor) d).executeAsyncScript(

” var callback =arguments[arguments.length – 1]; ” +
” var count=42; ” +
” setTimeout( collect, 0);” +
” function collect() { ” +
” if(count–>0) { “+
” setTimeout( collect, 0); ” +
” } “+
” else {callback(” +
” true” +
” );}”+
” } ”
));
}catch (Exception e) {
return Boolean.FALSE;
}
}
};
WebDriverWait w = new WebDriverWait(driver,timeOut);
w.until(javascriptDone);
w=null;

As a plus the countertop may be re-set on document.readyState or on jQuery Ajax calls or whether any jQuery cartoons are operating (simply if your program utilizes jQuery for ajax calls…)

” function collect() { ” +
” if(!((typeof jQuery === ‘undefined’) || ((jQuery.active === 0) && ($(\”:animated\”).length === 0))) && (document.readyState === ‘complete’)){” +
” count=42;” +
” setTimeout( collect, 0); ” +
” }” +
” else if(count–>0) { “+
” setTimeout( collect, 0); ” +
” } “+

MODIFY: I see executeAsyncScript does not function well if a fresh site lots and the evaluation may possibly cease reacting indefinitely, simpler to utilize this about alternatively.

public static ExpectedCondition<Boolean> documentNotActive(final int counter){
return new ExpectedCondition<Boolean>() {
boolean resetCount=true;
@Override
public Boolean apply(WebDriver d) {

if(resetCount){
((JavascriptExecutor) d).executeScript(
” window.mssCount=”+counter+”;\r\n” +
” window.mssJSDelay=function mssJSDelay(){\r\n” +
” if((typeof jQuery != ‘undefined’) && (jQuery.active !== 0 || $(\”:animated\”).length !== 0))\r\n” +
” window.mssCount=”+counter+”;\r\n” +
” window.mssCount–>0 &&\r\n” +
” setTimeout(window.mssJSDelay,window.mssCount+1);\r\n” +
” }\r\n” +
” window.mssJSDelay();”);
resetCount=false;
}

boolean ready=false;
try{
ready=-1==((Long) ((JavascriptExecutor) d).executeScript(
“if(typeof window.mssJSDelay!=\”function\”){\r\n” +
” window.mssCount=”+counter+”;\r\n” +
” window.mssJSDelay=function mssJSDelay(){\r\n” +
” if((typeof jQuery != ‘undefined’) && (jQuery.active !== 0 || $(\”:animated\”).length !== 0))\r\n” +
” window.mssCount=”+counter+”;\r\n” +
” window.mssCount–>0 &&\r\n” +
” setTimeout(window.mssJSDelay,window.mssCount+1);\r\n” +
” }\r\n” +
” window.mssJSDelay();\r\n” +
“}\r\n” +
“return window.mssCount;”));
}
catch (NoSuchWindowException a){
a.printStackTrace();
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
return ready;
}
@Override
public String toString() {
return String.format(“Timeout waiting for documentNotActive script”);
}
};
}

Leave a Reply

Your email address will not be published. Required fields are marked *