Selenium – Wait for AJAX request to complete – JavascriptExecutor executeAsyncScript

posted in: Selenium | 0

This guide demonstrates using JavascriptExecutor to make an AJAX request via executeAsyncScript and wait response data.

While executing a Selenium Script, consider a scenario where input data is to be fetched from the same site logged in. The simplest way to get data would be via AJAX request.

Why? Making requests using Java would require an authentication overhead. Instead the browser could make the ajax requests and return the required data.

Using Selenium for AJAX Request

The following code explains how it could be done. This code is based on example provided at Seleniumhq docs, but uses post request and jsoup for parsing HTML data. Read more about jsoup HTML parsing in my previous post.

[java]

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AsyncRequest {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin",
"D:\\Mozilla Firefox 10\\firefox.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_post2");
driver.manage().window().maximize();

JavascriptExecutor js = (JavascriptExecutor) driver;
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);

Object response = null;
try {
String data = "’fname=Henry&lname=Ford’;";
response = js.executeAsyncScript(
// Declare callback first!
"var callback = arguments[arguments.length – 1];"
+ "var http = new XMLHttpRequest();"
+ "var url = ‘demo_post2.asp’;"
+ "var params = "
+ data
+ "http.open(‘POST’, url, true);"
+ "http.setRequestHeader(‘Content-type’, ‘application/x-www-form-urlencoded’);"
+ "http.setRequestHeader(‘Content-length’, params.length);"
+ "http.setRequestHeader(‘Connection’, ‘close’);"
+ "http.onreadystatechange = function() {"
+ " if(http.readyState == 4) {"
+ " callback(http.responseText);" + " };"
+ "};" + "http.send(params);");
} catch (UnhandledAlertException e) {
System.err.println("Error Occured!");
}
Document doc = Jsoup.parse(response.toString());
System.out.println(doc.select("p").text());

}

}
[/java]

Leave a Reply

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