JavascriptExecutor js = (JavascriptExecutor) driver;js.executeScript(Stringscript,object... args);
第一行代码将driver强制转换为JavascriptExecutor
第二行代码是执行js,参数script是要执行的js语句,可以看到第二个参数在参数类型和参数名之间有…,
在Java里,这代表这个参数可以没有,也可以有1个或者多个。对于executeScript这个方法,取决于js语句是否需要参数。该方法返回值Boolean, Long, String, List or WebElement. 或者是 null.
JavascriptExecutor js = (JavascriptExecutor) driver;// 用js弹出alertjs.executeScript("alert('Test Case Execution Is started Now..');");driver.switchTo().alert().accept();// 用js判断页面加载完毕,返回completeSystem.out.println("readyState: "+ js.executeScript("return document.readyState").toString());// 用js得到页面的titleString title = (String) js.executeScript("return document.title");System.out.println("current page title get by js: "+ title);// 用js得到页面的domain nameSystem.out.println("current page domain name get by js: "+ js.executeScript("return document.domain"));// 用js操作页面元素,如高亮显示某个元素WebElement element = driver.findElement(By.id("kw"));js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element,"color: orange; border: 4px solid orange;");/**
* 每隔一秒check一下页面加载是否完成,check次数是25
*/publicvoidcheckPageIsReady() { JavascriptExecutor js = (JavascriptExecutor) driver;for(inti =0; i <25; i++) {if("complete".equals(js .executeScript("return document.readyState").toString())) {break; }try{ Thread.sleep(1000); }catch(InterruptedException e) { e.printStackTrace(); } }}