These are pulled directly from the Selenium JavaDoc which is available here:
http://selenium.googlecode.com/git/docs/api/java/index.html
Example #1: Performing a sleep in the browser under test.
long start = System.currentTimeMillis();
((JavascriptExecutor) driver).executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 500);");
System.out.println("Elapsed time: " + System.currentTimeMillis() - start);
Example #2: Synchronizing a test with an AJAX application
WebElement composeButton = driver.findElement(By.id("compose-button"));
composeButton.click();
((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"mailClient.getComposeWindowWidget().onload(callback);");
driver.switchTo().frame("composeWidget");
driver.findElement(By.id("to")).sendKeys("[email protected]");
Example #3: Injecting a XMLHttpRequest and waiting for the result:
Object response = ((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '/resource/data.json', true);" +
"xhr.onreadystatechange = function() {" +
" if (xhr.readyState == 4) {" +
" callback(xhr.responseText);" +
" }" +
"}" +
"xhr.send();");
JSONObject json = new JSONObject((String) response);
assertEquals("cheese", json.getString("food"));
WebElementdirectly?