List of usage examples for org.openqa.selenium JavascriptExecutor executeScript
Object executeScript(String script, Object... args);
From source file:com.vaadin.tests.components.grid.basicfeatures.GridBasicFeaturesTest.java
License:Apache License
private Object executeScript(String script, WebElement element) { final WebDriver driver = getDriver(); if (driver instanceof JavascriptExecutor) { final JavascriptExecutor je = (JavascriptExecutor) driver; return je.executeScript(script, element); } else {/* www . j av a 2 s . c o m*/ throw new IllegalStateException("current driver " + getDriver().getClass().getName() + " is not a " + JavascriptExecutor.class.getSimpleName()); } }
From source file:com.vaadin.tests.components.grid.basicfeatures.GridClientDataSourcesTest.java
License:Apache License
private Object executeScript(String script, Object args) { final WebDriver driver = getDriver(); if (driver instanceof JavascriptExecutor) { final JavascriptExecutor je = (JavascriptExecutor) driver; return je.executeScript(script, args); } else {/*ww w.j ava2 s . com*/ throw new IllegalStateException("current driver " + getDriver().getClass().getName() + " is not a " + JavascriptExecutor.class.getSimpleName()); } }
From source file:com.vilt.minium.impl.JQueryInvoker.java
License:Apache License
@SuppressWarnings("unchecked") public <T> T invoke(JavascriptExecutor wd, boolean async, String expression, Object... args) { try {// w w w .j ava 2 s.c o m args = convertToValidArgs(args); Object[] fullArgs = args == null ? new Object[1] : new Object[args.length + 1]; fullArgs[0] = async; if (args != null) System.arraycopy(args, 0, fullArgs, 1, args.length); Object result = async ? wd.executeAsyncScript(lightInvokerScript(expression), fullArgs) : wd.executeScript(lightInvokerScript(expression), fullArgs); if (result instanceof Boolean && !((Boolean) result).booleanValue()) { fullArgs = args == null ? new Object[2] : new Object[args.length + 2]; fullArgs[0] = async; fullArgs[1] = styles; if (args != null) System.arraycopy(args, 0, fullArgs, 2, args.length); result = async ? wd.executeAsyncScript(fullInvokerScript(expression), fullArgs) : wd.executeScript(fullInvokerScript(expression), fullArgs); } if (!(result instanceof List)) throw new IllegalStateException(format("Expected a list with the result in the first position...")); List<?> resultAsList = (List<?>) result; // results can only be empty if it was a result of a jQuery evaluation if (resultAsList.isEmpty()) return (T) Collections.emptyList(); if (resultAsList.get(0) instanceof WebElement) { // it's an array of web elements return (T) resultAsList; } return (T) resultAsList.get(0); } catch (Exception e) { throw new WebElementsException(e); } }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Clicks on a link, button, checkbox or radio button. If the click action * causes a new page to load (like a link usually does), call * waitForPageToLoad. <br>/*from w w w . jav a 2 s. c o m*/ * * @param locator * the locator */ private void doClick(final ObjectLocator locator) { String objectID = ""; int counter = getRetryCount(); WebDriver driver = getDriver(); try { // Retrieve the correct object locator from the object map objectID = locator.getActualLocator(); // first verify whether the element is present in the current web // page checkForNewWindowPopups(); WebElement element = checkElementPresence(objectID); /* * START DESCRIPTION following while loop was added to make the * command more consistent try the command for give amount of time * (can be configured through class variable RETRY) command will be * tried for "RETRY" amount of times untill command works. any * exception thrown within the tries will be handled internally. * * can be exitted from the loop under 2 conditions 1. if the command * succeeded 2. if the RETRY count is exceeded */ while (counter > 0) { try { counter--; // call for real selenium command /* selenium.click(objectID); */ element.click(); // if not exception is called consider and report the result // as passed reportresult(true, "CLICK :" + locator.getLogicalName() + "", "PASSED", ""); // if the test case passed move out from the loop break; } catch (StaleElementReferenceException staleElementException) { element = checkElementPresence(objectID); } catch (ElementNotVisibleException ex) { try { JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; jsExecutor.executeScript("arguments[0].click();", element); reportresult(true, "CLICK :" + locator.getLogicalName() + "", "PASSED", ""); break; } catch (Exception e) { e.printStackTrace(); continue; } } catch (Exception e) { sleep(retryInterval); String objectName = locator.getLogicalName(); if (!(counter > 0)) { e.printStackTrace(); reportresult(true, "CLICK :" + objectName + "", "FAILED", "CLICK command cannot access Element (" + objectName + ") [" + objectID + "] "); checkTrue(false, true, "CLICK command cannot access Element (" + objectName + ") [" + objectID + "] "); } } } /* * END DESCRIPTION */ } catch (Exception e) { e.printStackTrace(); String objectName = locator.getLogicalName(); /* * VTAF result reporter call */ reportresult(true, "CLICK :" + objectName + "", "FAILED", "CLICK command :Element (" + objectName + ") [" + objectID + "] not present"); /* * VTAF specific validation framework reporting */ checkTrue(false, true, "CLICK command :Element (" + objectName + ") [" + objectID + "] not present"); } }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * internal method which actually checks whether the given element is * exists./*from w w w.ja va 2 s .c o m*/ * * @param searchPath * the search path * @return the web element * @throws Exception * the exception */ private WebElement checkElementPresence(final String searchPath) throws Exception { WebDriver driver = getDriver(); WebElement webElement = null; String locator = searchPath; final Logger log = getLog(); int count = getRetryCount(); setCommandStartTime(getCurrentTime()); final By searchBy = getLocatorType(locator); final Long retryMillis = 1000L; try { Function<WebDriver, WebElement> findElementFunction = new FindElementFunction<WebDriver, WebElement>( searchBy); Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout((count * retryMillis), TimeUnit.MILLISECONDS) .pollingEvery(retryInterval, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class) .ignoring(WebDriverException.class); webElement = wait.until(findElementFunction); } catch (Exception e) { log.error("Element [ " + searchPath + " ] Not Found", e); } if (webElement != null) { try { log.info("Element [ " + searchBy.toString() + " ] Found"); JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; jsExecutor.executeScript("arguments[0].scrollIntoView(false);", webElement); } catch (Exception ex) { log.error("Exception occured while scrolling to the element.", ex); } } else { throw new Exception("Element " + searchPath); } return webElement; }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Checks the contents of a multi color bar chart against the expected * values.//ww w .j av a 2 s .c o m * * @param userColumns * @param chartElementXpath * @param */ @SuppressWarnings("rawtypes") private StringBuffer insightColorBarChartContentCheck(String chartName, String chartLocator, ArrayList<String> chartnames, ArrayList<String> chartvalues, ArrayList<String> chartpercentages, int startingele, int checkingColCount, HashMap<Integer, ArrayList> userColumns, String chartElementCapture, String chartElementXpath) { // Portlet content variables WebDriver driver = getDriver(); ArrayList<String> chartelementnames = chartnames; ArrayList<String> chartelementvalues = chartvalues; // ArrayList<String> chartpercentage = chartpercentages; int startingelement = startingele; int arraycounter = 0; StringBuffer verificationErrors = new StringBuffer(); int actCategoryCount = 0; int actElementCnt = 0; int elementOffset = 0; ArrayList<String> htmlElementNames = new ArrayList<String>(); ArrayList<String> htmlElementValues = new ArrayList<String>(); // chathura HashMap<Integer, ArrayList> htmlColumns = new HashMap<Integer, ArrayList>(); ArrayList htmlColumnValues = new ArrayList(); JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; Actions action = new Actions(driver); if (chartName.contains("text")) { elementOffset = 3; } else if (chartName.contains("img")) { elementOffset = 2; } List<WebElement> locateElementsThree = driver .findElements(By.xpath(chartName + "//child::*[position()=2 and name()='g']/child::*[position()=2 " + "and name()='g']/child::*[name()='rect']")); actCategoryCount = locateElementsThree.size(); List<WebElement> locateElementsFour = driver .findElements(By.xpath(chartName + "//child::*[position()=2 and name()='g']")); actElementCnt = locateElementsFour.size(); int rectFormat = actCategoryCount / actElementCnt; // The first loop of the pie chart check for (int i = startingelement; i <= rectFormat; i++) { // Accessing the different colored elements in a bar // ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT // ELEMENT ELEMENT ELEMENT htmlElementNames = new ArrayList<String>(); htmlElementValues = new ArrayList<String>(); htmlColumnValues = new ArrayList<>(); for (int colorFieldRect = i; colorFieldRect <= actCategoryCount; colorFieldRect += rectFormat) { try { try { WebElement chartHeaderEle = driver.findElement(By.xpath(chartElementXpath)); jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" + "arguments[0].dispatchEvent(evObj);", chartHeaderEle); WebElement element = driver.findElement(By.xpath(chartName + "//child::*[position()=2 and name()='g']/child::*[position()=2 and name()='g']")); jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" + "arguments[0].dispatchEvent(evObj);", element); System.out.println(element); Thread.sleep(500); WebElement element2 = driver.findElement(By.xpath(chartName + "//child::*[position()=2 and name()='g']/child::*[position()=2 and name()='g']/child::*[position()=" + colorFieldRect + " and name()='rect']")); jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" + "arguments[0].dispatchEvent(evObj);", element2); System.out.println(element2); Thread.sleep(500); } catch (Exception ex) { if (ex.getMessage().contains("Alert")) { if (ex.getMessage().contains("Alert")) { WebElement element3 = driver.findElement(By.xpath(chartName + "//child::*[position()=2 and name()='g']/child::*[position()=2 and name()='g']/child::*[position()=" + colorFieldRect + " and name()='rect']")); jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" + "arguments[0].dispatchEvent(evObj);", element3); } } } try { driver.findElements(By.xpath(chartName + "//child::*[name()='g' and position()=" + (actElementCnt + elementOffset) + "]")); } catch (Error e) { verificationErrors.append("\n" + e.toString()); } try { String chartstr12 = driver.findElement(By.xpath(chartName + "/..//child::*[position()=1 and name()='svg']/child::*[name()='g' and position()=" + (actElementCnt + elementOffset) + "]//*[name()='text' and position()=" + 1 + "]")).getText(); System.out.println("chartstr12 : " + chartstr12); htmlElementNames.add(chartstr12); } catch (Error e) { verificationErrors.append("\n" + e.toString()); } try { String chartstr22 = driver.findElement(By.xpath(chartName + "/..//child::*[position()=1 and name()='svg']/child::*[name()='g' and position()=" + (actElementCnt + elementOffset) + "]//*[name()='text' and position()=" + 2 + "]")).getText(); System.out.println("chartstr22 : " + chartstr22); htmlElementValues.add(chartstr22); } catch (Error e) { verificationErrors.append("\n" + e.toString()); } arraycounter = arraycounter + 1; } catch (Error e) { verificationErrors.append("\n" + e.toString()); } catch (Exception e1) { verificationErrors.append("\n" + e1.toString()); } } // end of second for loop htmlColumnValues.add(htmlElementNames); htmlColumnValues.add(htmlElementValues); htmlColumns.put(i, htmlColumnValues); } // end of first for loop for (int i = 1; i <= userColumns.size(); i++) { int checkingHtmlColumn = -1; for (int j = 1; j <= htmlColumns.size(); j++) { if (((ArrayList) userColumns.get(i).get(0)).get(0) .equals(((ArrayList) htmlColumns.get(j).get(0)).get(0))) { checkingHtmlColumn = j; break; } } // check if the if (checkingHtmlColumn < 0) { verificationErrors.append("\n Element :" + i + " Input column name : " + ((ArrayList) userColumns.get(i).get(0)).get(0) + " cannot be found in the chart"); continue; } else { ArrayList currUserColumnNames = ((ArrayList) userColumns.get(i).get(0)); ArrayList currUserColumnValues = ((ArrayList) userColumns.get(i).get(1)); ArrayList currHtmlColumnNames = ((ArrayList) htmlColumns.get(checkingHtmlColumn).get(0)); ArrayList currHtmlColumnValues = ((ArrayList) htmlColumns.get(checkingHtmlColumn).get(1)); for (int k = 0; k < currHtmlColumnValues.size(); k++) { if (currHtmlColumnValues.get(k).equals("0") || currHtmlColumnValues.get(k) == null) { currHtmlColumnNames.remove(k); currHtmlColumnValues.remove(k); k--; } } // Checking the column names if (currHtmlColumnNames.equals(currUserColumnNames)) { } else { verificationErrors.append("\n Element :" + i + " Expected element names = " + userColumns.get(i).get(0) + " are different from the " + "actual names : " + htmlColumns.get(checkingHtmlColumn).get(0) + " | "); } // Checking the column values if (currHtmlColumnValues.equals(currUserColumnValues)) { } else { verificationErrors.append("\n Element :" + i + " Expected element values = " + userColumns.get(i).get(1) + " are different from the " + "actual values : " + htmlColumns.get(checkingHtmlColumn).get(1) + " | "); } } } return verificationErrors; }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Checks the contents of a pie chart against the expected values. * /* w ww . j a v a2 s . c o m*/ * @param chartElementXpath */ private StringBuffer insightPieChartContentCheck(String chartName, ArrayList<String> chartnames, ArrayList<String> chartvalues, ArrayList<String> chartpercentages, int startingele, String chartElementXpath) { // Portlet content variables WebDriver driver = getDriver(); ArrayList<String> chartelementnames = chartnames; ArrayList<String> chartelementvalues = chartvalues; ArrayList<String> chartpercentage = chartpercentages; ArrayList<String> chartelementnamesAct = new ArrayList<String>(); ArrayList<String> chartelementvaluesAct = new ArrayList<String>(); int startingelement = startingele; int arraycounter = 0; StringBuffer verificationErrors = new StringBuffer(); int elementCount = 0; JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; // Checking chart structure // The first loop of the pie chart check // Accessing the elements in the pie chart // ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT // ELEMENT ELEMENT ELEMENT try { int countA = 0; List<WebElement> locateElements = driver .findElements(By.xpath("" + chartName + "//*[name()='svg']/child::*[name()='g']")); countA = locateElements.size(); int categories = countA - 2; for (int j = startingelement; j < categories + startingelement; j++) { System.out.println("" + chartName + "//*[name()='svg']/child::*[position()=" + (j) + "]"); WebElement chartElement = driver.findElement(By.xpath(chartElementXpath)); jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" + "arguments[0].dispatchEvent(evObj);", chartElement); Thread.sleep(1000); WebElement element = driver.findElement( By.xpath("" + chartName + "//*[name()='svg']/child::*[position()=" + (j) + "]")); jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" + "arguments[0].dispatchEvent(evObj);", element); try { driver.findElements(By.xpath("" + chartName + "//*[name()='svg']/child::*[position()=" + (chartelementnames.size() + startingelement) + "]")); } catch (Error e) { verificationErrors.append("\n" + e.toString()); } Thread.sleep(500); int countB = 0; List<WebElement> locateElementsTwo = driver .findElements(By.xpath("" + chartName + "//*[name()='svg']/child::*[name()='g']")); countB = locateElementsTwo.size(); elementCount = countB; if (elementChartElementPresent("" + chartName + "//*[name()='svg']/child::*[position()=" + (categories + 4) + "]/child::*[position()=1]/child::*[position()=4]")) { String xpath = "" + chartName + "//*[name()='svg']/child::*[position()=" + (categories + 4) + "]/child::*[position()=1]/child::*[position()=4]"; System.out.println("XPATH :" + xpath); chartelementnamesAct.add(driver .findElement(By.xpath("" + chartName + "//*[name()='svg']/child::*[position()=" + (categories + 4) + "]/child::*[position()=1]/child::*[position()=4]")) .getText()); } System.out.println("chartelementnamesAct : " + chartelementnamesAct); if (elementChartElementPresent("" + chartName + "//*[name()='svg']/child::*[position()=" + (categories + 4) + "]/child::*[position()=1]/child::*[position()=5]")) { chartelementvaluesAct.add(driver .findElement(By.xpath("" + chartName + "//*[name()='svg']/child::*[position()=" + (categories + 4) + "]/child::*[position()=1]/child::*[position()=5]")) .getText()); System.out.println("chartelementvaluesAct:" + chartelementvaluesAct); } } for (int i = 0; i < chartelementnames.size(); i++) { String expectedname = "" + chartelementnames.get(i) + ""; String expectedPers = "" + chartelementvalues.get(i) + " (" + chartpercentage.get(i) + "%)"; if (chartelementnamesAct.contains(expectedname)) { if (chartelementvaluesAct.contains(expectedPers)) { } else { verificationErrors .append("\n Chart comparison mismatch : percentage " + expectedPers + " is not present in the actual percentage values " + expectedname) .append(chartelementvaluesAct); } } else { verificationErrors .append("\n Chart comparison mismatch : category name " + expectedname + " is not present in the actual percentage values ") .append(chartelementnamesAct); } } } catch (Exception e) { verificationErrors.append("\n" + e.toString()); } return verificationErrors; }
From source file:com.westconcomster.MO365.java
public void mo365Order(WebDriver driver, String region) throws InterruptedException { String winHandleBefore = driver.getWindowHandle(); Thread.sleep(10000);//ww w . ja v a 2s . co m driver.findElement(By.xpath("//p[contains(.,'Buy Now')]")).click(); //Select the customer for (String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); System.out.println(">>>>>>>>>>inside child window"); //Search for the customer Thread.sleep(5000); WebElement searchCust = driver.findElement(By.xpath("(.//*[@id='search_value'])[4]")); searchCust.clear(); searchCust.sendKeys(Constants.companyName); Thread.sleep(5000); driver.findElement(By.xpath( ".//*[@id='customersList']/div[1]/ul/div[1]/div/div[2]/div/ecommerceselectable-customer/div/div[3]/div")) .click(); //Select MO365 WebElement searchProduct = driver.findElement(By.xpath("(.//*[@id='search_value'])[5]")); searchProduct.clear(); searchProduct.sendKeys("MO365"); Thread.sleep(2000); driver.findElement(By.xpath("//ecommerceselectable-product/div/div[3]/div/p")).click(); (new WebDriverWait(driver, 60)) .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='quoteName']"))) .sendKeys("LATAM_MO365_Order"); Select dropdown = new Select(driver.findElement(By.name("root[contract][supportLevel]"))); dropdown.selectByIndex(1); //Add reseller Margin driver.findElement(By.name("root[contract][resellermargin]")).clear(); driver.findElement(By.name("root[contract][resellermargin]")).sendKeys("10"); System.out.println(">>>>>>>Reseller Margin Added"); driver.findElement(By.name("root[contract][billenduser]")).click(); System.out.println(">>>>>>>>Bill End User"); JavascriptExecutor jse = (JavascriptExecutor) driver; jse.executeScript("window.scrollBy(0,350)", ""); Thread.sleep(5000); //select license MO365Licences mo365lic = new MO365Licences(); mo365lic.mo365Licences(driver, region); //Select MO365 Add-ons MO365AddOns moadd = new MO365AddOns(); moadd.mo365AddOns(driver, region); //Select Westcon Services MO365WestconServices mo365WS = new MO365WestconServices(); mo365WS.mo365WestconServices(driver, region); //Total price WebElement price = (new WebDriverWait(driver, 60)).until( ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[text()[contains(.,'Total:')]]"))); String totalAmt = price.getText().substring(price.getText().indexOf(":") + 1).trim(); System.out.println(">>>>>>>>>>>TotalAmount" + totalAmt); //Click Next Button (new WebDriverWait(driver, 20).until( ExpectedConditions.visibilityOfElementLocated(By.xpath(".//button[contains(text(),'Next')]")))) .click(); Thread.sleep(10000); driver.findElement(By.xpath(".//button[contains(text(),'Submit Order')]")).click(); //Add domain WebElement domain1 = (new WebDriverWait(driver, 30).until(ExpectedConditions .visibilityOfElementLocated(By.xpath("//input[@name='root[microsoft_info][domain_prefix]']")))); domain1.sendKeys(Constants.domian); domain1.sendKeys(Keys.TAB); Thread.sleep(10000); //Click on Submit Order WebElement submit = (new WebDriverWait(driver, 20).until(ExpectedConditions .visibilityOfElementLocated(By.xpath("//button[contains(text(),'Submit Order')]")))); submit.click(); System.out.println(">>>>>>>>Order Submitted "); Thread.sleep(10000); //PO Number String orderNumber = driver.findElement(By.xpath(".//ecommercewizardstep[4]/section/div/div[2]/p")) .getText().replaceAll("\\D", "").trim(); ; System.out.println(">>>>>>>>>>>Order number" + orderNumber); //Click on Close Button driver.findElement(By.xpath("//ecommercewizardstep[4]/section/div/div[2]/article/button[2]")).click(); driver.switchTo().window(winHandleBefore); //*******Verify Order on Portal Thread.sleep(10000); String orderScreenOrder = driver.findElement(By.xpath( ".//*[@id='orders']/div/section[2]/div[1]/div[2]/div/div[2]/div/order/div[1]/div/div[1]/div[3]/div/div[1]/div[2]/div[2]")) .getText(); System.out.println(">>>>>>>>>> OrderID" + orderScreenOrder); if (orderScreenOrder.equals(orderNumber)) { System.out.println(">>>>>> PASS <<<<<<< MO365 Order Created Successfully on portal"); } else { System.out.println("Order FAILED"); } } }
From source file:com.wikia.webdriver.pageobjectsfactory.pageobject.WikiBasePageObject.java
License:Open Source License
public Object[] getWgVariableKeysFromPage(String url, String variableName) { getUrl(url);/*from ww w . j a v a 2 s . c om*/ JavascriptExecutor js = (JavascriptExecutor) driver; Map<String, Integer> variableValueFromPage = (Map<String, Integer>) js .executeScript("return eval(arguments[0])", variableName); return variableValueFromPage.keySet().toArray(); }
From source file:common.KeywordBase.java
License:Apache License
/** * Will perform javascript actions for an element * /* ww w .jav a 2 s. c o m*/ * @param value * Value * @param locator * HTML element locator from Object Repository file. * @param index * (Optional) Index of an element. Applies only if more than 1 * element present in HTML. 0 by default. */ public synchronized void executeScript(String value, String locator, String... index) { JavascriptExecutor js = (JavascriptExecutor) driver(); js.executeScript(value, getElement(locator, index)); }