这些是直接从 Selenium JavaDoc 中提取的,可在此处获得:
http://selenium.googlecode.com/git/docs/api/java/index.html
示例 #1:在被测浏览器中执行休眠。
long start = System.currentTimeMillis();
((JavascriptExecutor) driver).executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 500);");
System.out.println("Elapsed time: " + System.currentTimeMillis() - start);
示例 #2:将测试与 AJAX 应用程序同步
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("bog@example.com");
示例 #3:注入 XMLHttpRequest 并等待结果:
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"));