Example usage for org.openqa.selenium JavascriptExecutor executeScript

List of usage examples for org.openqa.selenium JavascriptExecutor executeScript

Introduction

In this page you can find the example usage for org.openqa.selenium JavascriptExecutor executeScript.

Prototype

Object executeScript(String script, Object... args);

Source Link

Document

Executes JavaScript in the context of the currently selected frame or window.

Usage

From source file:gov.nasa.jpl.memex.nutch.protocol.selenium.handlers.Pagination.PaginationHandler18.java

License:Apache License

public void processSlickGuns(WebDriver driver) {
    try {//from w ww  . j  a va  2 s  .c o  m
        int page = 0;
        String str1 = "<html><body><p>";
        while (true) {
            page++;
            List<WebElement> ele = driver.findElements(By.tagName("a"));
            for (WebElement we : ele) {
                str1 += "<a href='" + (String) we.getAttribute("href") + ">" + (String) we.getAttribute("href")
                        + "</a><br>";
            }
            try {
                // check if the next page is present
                // WebElement page_num = driver.findElement(By.xpath("//a[text()='"+ page +"']"));
                String pagestr = "page=" + page;
                String s1 = "a[href*='" + pagestr + "']";
                WebElement page_num = driver.findElement(By.cssSelector(s1));
                page_num.click();
            } catch (NoSuchElementException ex) {
                // end of pagination
                break;
            }
        }
        JavascriptExecutor js = (JavascriptExecutor) driver;
        str1 += "</p></body></html>";
        js.executeScript("document.body.innerHTML=arguments[0]", str1);
    } catch (NoSuchElementException ex) {
        // no pagination found
    }
}

From source file:gov.nasa.jpl.memex.nutch.protocol.selenium.handlers.Pagination.PaginationHandler18.java

License:Apache License

public void vci_classifieds(WebDriver driver) {

    driver.manage().window().maximize();
    //to hover over the Ad Category button and click it
    driver.findElement(By.xpath("/html/body//a[@id='categorylink']")).click();
    //Hover over to firearm category and click Handguns
    WebElement element1 = driver.findElement(By.xpath("/html/body/div[3]/div/div/div[3]/ul/li[4]/a"));
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element1);
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    List<WebElement> w1 = driver.findElements(By.xpath("html/body//div[@id='adlist']/table[3]//a"));
    for (WebElement ele : w1) {
        String str1;/*from  ww  w .j  a v a2  s. co  m*/
        str1 = ele.getAttribute("href");
        int begin = str1.indexOf("(") + 2;
        if (begin < 0)
            continue;
        int end = str1.indexOf(")") - 1;
        if (end < 0)
            continue;
        String adId = str1.substring(begin, end);
        String url = "https://www.vci-classifieds.com/a-getad.php?id=" + adId;
        executor.executeScript("$.get(arguments[0], function(data) { $('#fb-root').html(data); } );", url);
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
    }

    element1 = driver.findElement(By.xpath("/html/body/div[3]/div/div/div[3]/ul/li[5]/a"));
    executor.executeScript("arguments[0].click();", element1);
}

From source file:imagedownload.Downloader.java

private String getXpath(WebDriver driver, WebElement elm, String currentPath) {
    System.out.println("Current path: " + currentPath);
    StringBuilder path = new StringBuilder();
    path.append("/" + elm.getTagName());
    path.append(currentPath);//w  w  w .  j  a va 2  s  .  c o m
    //        if(elm.getAttribute("id")!=null && !elm.getAttribute("id").equals("")){
    //            subPath.append("[@id='"+elm.getAttribute("id")+"']");
    //        }else if(elm.getAttribute("class")!=null && !elm.getAttribute("class").equals("")){
    //            subPath.append("[@class='"+elm.getAttribute("class")+"']");
    //        }
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    WebElement parentElement = (WebElement) executor.executeScript("return arguments[0].parentNode;", elm);
    return (elm.getTagName().equalsIgnoreCase("html") || parentElement == null) ? path.toString()
            : getXpath(driver, parentElement, path.toString());
}

From source file:io.github.blindio.prospero.core.browserdrivers.WebDriverDriver.java

License:Apache License

public String executeJavascript(String javascript) {
    String returnVal = null;/*from   w w w.  j a v  a  2  s.  c  o m*/
    try {
        JavascriptExecutor jse = (JavascriptExecutor) webdriver;
        returnVal = jse.executeScript(javascript, (Object[]) null).toString();
    } catch (ClassCastException cce) {
        // TODO
    }
    return returnVal;
}

From source file:io.github.mmichaelis.selenium.client.provider.AbstractWebDriverProviderTest.java

License:Apache License

private void prepareResetTest(final HtmlUnitDriver testedDriver)
        throws InterruptedException, ExecutionException {
    final URL otherPageUrl = Resources.getResource(this.getClass(), "page2.html");
    final URL newPageUrl = Resources.getResource(this.getClass(), "page3.html");
    final WebDriverProvider driverProvider = new NoExceptionWebDriverProvider(testedDriver);
    final ExecutorService executorService = newCachedThreadPool();
    final Future<Void> openWindowResultFuture = executorService.submit(new Callable<Void>() {
        @Nullable//  ww  w  . j a  va  2s.  com
        @Override
        public Void call() {
            final WebDriver driver = driverProvider.get();
            driver.get(otherPageUrl.toExternalForm());
            final JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("window.open(arguments[0])", newPageUrl.toExternalForm());
            final Set<String> windowHandles = driver.getWindowHandles();
            checkState(windowHandles.size() > 1, "Failed to open additional window for driver: %s", driver);
            driverProvider.reset();
            return null;
        }
    });
    openWindowResultFuture.get();
}

From source file:io.github.seleniumquery.functions.jquery.events.ClickFunction.java

License:Apache License

private static SeleniumQueryObject click(SeleniumQueryObject seleniumQueryObject, boolean isWaitView) {
    List<WebElement> elements = seleniumQueryObject.get();

    int numberOfNotClickedElements = 0;
    Exception lastCaughtException = null;
    WebElement elementThatThrewLastCaughtException = null;

    for (WebElement element : elements) {
        try {//from w w w .j  a v  a 2  s  .c o  m
            if (isWaitView) { //Avoiding errors with ChromeHeadless.
                LOGGER.debug("Waiting " + seleniumQueryObject + " becoming visible.");
                seleniumQueryObject.waitUntil().is(":visible");

                LOGGER.debug("Viewing " + seleniumQueryObject + ".");
                JavascriptExecutor js = (JavascriptExecutor) seleniumQueryObject.getWebDriver();
                js.executeScript("arguments[0].scrollIntoView()", element);
            }

            LOGGER.debug("Clicking " + seleniumQueryObject + ".");
            element.click();
        } catch (ElementNotVisibleException e) {
            numberOfNotClickedElements++;
            lastCaughtException = e;
            elementThatThrewLastCaughtException = element;
        }
    }

    reportIfThereWasAnyElementNotClicked(LOGGER, seleniumQueryObject, elements, numberOfNotClickedElements,
            lastCaughtException, elementThatThrewLastCaughtException);
    return seleniumQueryObject;
}

From source file:io.github.seleniumquery.functions.jquery.events.DoubleClickFunction.java

License:Apache License

private void doubleClick(WebElement element, WebDriver webDriver) {
    /* #Cross-Driver/*  www.  java  2 s.  co  m*/
     *
     * SAFARI does not implement the "mouseMoveTo" action!
     * org.openqa.selenium.WebDriverException: Unknown command: {"id":"e4rhawdodv9u","name":"mouseMoveTo","parameters":{"element":":wdc:1467681082384"}}
     *
     * EDGE never fires the dblclick event using actions (and is silent about it :|).
     *
     * FIREFOX latest geckodriver (0.19.1 + ff 57) does not trigger dblclick even as well...
     */
    if (DriverVersionUtils.isSafariDriver(webDriver) || DriverVersionUtils.isEdgeDriver(webDriver)
            || DriverVersionUtils.isFirefoxDriver(webDriver)) {
        element.click();
        element.click();
        JavascriptExecutor js = (JavascriptExecutor) webDriver;
        js.executeScript(
                "arguments[0].dispatchEvent(new MouseEvent('dblclick',{'view':window,'bubbles':true,'cancelable':true}));",
                element);
    } else {
        new Actions(webDriver).doubleClick(element).perform();
    }
}

From source file:io.github.seleniumquery.functions.jquery.manipulation.HtmlFunction.java

License:Apache License

private static String getHtmlUnitInnerHTML(HtmlUnitWebElement element) {
    WebDriver driver = element.getWrappedDriver();
    // we resort to JavaScript when it is enabled
    if (((HtmlUnitDriver) driver).isJavascriptEnabled()) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        return js.executeScript("return arguments[0].innerHTML", element).toString();
    }/*from  w w w . j a v  a  2s.com*/

    // or use reflection if JS is not enabled
    // (this method is not preferred as it relies on HtmlUnit's internals, which can change without notice)
    try {
        // #HtmlUnit #reflection #hack
        Method getElementMethod = HtmlUnitWebElement.class.getDeclaredMethod("getElement");
        getElementMethod.setAccessible(true);

        HtmlElement he = (HtmlElement) getElementMethod.invoke(element);
        HTMLElement e = (HTMLElement) he.getScriptableObject();

        return e.getInnerHTML();
    } catch (Exception e) {
        LOGGER.warn("Unable to get WebElement's innerHTML. Returning empty string.", e);
        return "";
    }
}

From source file:javax.portlet.tck.driver.TCKSimpleTestDriver.java

License:Apache License

/**
 * Tries to access the page for the test case. Looks for the page link
 * and clicks it, waiting for the page to load.
 * //from  w  ww  .j  ava 2  s . co m
 * @return  a list of elements for the TC (should only be one)
 */
protected List<WebElement> accessPage() throws Exception {
    List<WebElement> wels = driver.findElements(By.linkText(page));
    debugLines.add("   Access page, link found: " + !wels.isEmpty() + ", page===" + page + "===");

    if (wels.isEmpty()) {
        // retry through login page
        debugLines.add("   logging in ... ");
        login();
        wels = driver.findElements(By.linkText(page));
        if (wels.isEmpty()) {
            throw new Exception("Page " + page + ": link could not be found.");
        }
    }

    WebElement wel = wels.get(0);
    if (scroll) {
        JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
        javascriptExecutor.executeScript(
                "window.scrollTo(0, (arguments[0].getBoundingClientRect().top + window.pageYOffset) - (window.innerHeight / 2));",
                wel);
    }
    wel.click();
    WebDriverWait wdw = new WebDriverWait(driver, timeout);
    wdw.until(ExpectedConditions.visibilityOfElementLocated(By.name(tcName)));
    wels = driver.findElements(By.name(tcName));
    if (wels.isEmpty()) {
        throw new Exception("For test case " + tcName + ": no elements found.");
    }
    return wels;
}

From source file:javax.portlet.tck.driver.TCKSimpleTestDriver.java

License:Apache License

/**
 * Looks for a link or button that can be clicked for the TC and clicks it if found.
 * /*from   ww w  .ja  v a  2  s . c om*/
 * First looks for a test case setup link or button and clicks it if found. Then it 
 * looks for a test case execution link and clicks it if found. 
 * 
 * @return  web element list containing the test case results.
 * @throws Exception 
 */
@SuppressWarnings("unused")
protected List<WebElement> processClickable(List<WebElement> wels) throws Exception {
    String setupId = tcName + Constants.SETUP_ID;
    String actionId = tcName + Constants.CLICK_ID;
    String resultId = tcName + Constants.RESULT_ID;
    String detailId = tcName + Constants.DETAIL_ID;
    String asyncId = tcName + Constants.ASYNC_ID;
    String notreadyId = tcName + Constants.NOTREADY_ID;
    List<WebElement> tcels = null;

    for (WebElement wel : wels) {
        tcels = wel.findElements(By.id(setupId));
        if (!tcels.isEmpty())
            break;
    }
    debugLines.add("   Setup link found: " + ((tcels != null) && !tcels.isEmpty()));

    // If were dealing with async, make sure the JavaScript is initialized
    List<WebElement> acels = driver.findElements(By.id(asyncId));
    debugLines.add("   Async elements found: " + ((acels != null) && !acels.isEmpty()));
    if (acels != null && !acels.isEmpty()) {
        WebDriverWait wdw = new WebDriverWait(driver, timeout);
        wdw.until(ExpectedConditions.invisibilityOfElementLocated(By.id(notreadyId)));
        debugLines.add("   Async elements are now ready.");
    }

    // Click setup link if found
    if ((tcels != null) && !tcels.isEmpty()) {
        WebElement wel = tcels.get(0);
        if (scroll) {
            JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
            javascriptExecutor.executeScript(
                    "window.scrollTo(0, (arguments[0].getBoundingClientRect().top + window.pageYOffset) - (window.innerHeight / 2));",
                    wel);
        }
        wel.click();
        debugLines.add("   Clicked setup link.");

        WebDriverWait wdw = new WebDriverWait(driver, timeout);

        String expr = "//*[@id='" + resultId + "'] | //*[@id='" + actionId + "']";
        debugLines.add("   xpath string: ===" + expr + "===");

        wdw.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(expr)));
        wels = driver.findElements(By.name(tcName));

        debugLines.add("   Found elements: " + (!wels.isEmpty()));
        List<WebElement> xels = driver.findElements(By.xpath(expr));
        for (WebElement w : xels) {
            debugLines.add("      Element: " + w.getTagName() + ", id=" + w.getAttribute("id"));
        }
    }

    // Now click the action link, if present
    for (WebElement wel : wels) {
        tcels = wel.findElements(By.id(actionId));
        if (!tcels.isEmpty())
            break;
    }
    debugLines.add("   Clickable link found: " + ((tcels != null) && !tcels.isEmpty()));

    if (tcels != null && !tcels.isEmpty()) {
        WebElement wel = tcels.get(0);
        if (scroll) {
            JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
            javascriptExecutor.executeScript(
                    "window.scrollTo(0, (arguments[0].getBoundingClientRect().top + window.pageYOffset) - (window.innerHeight / 2));",
                    wel);
        }
        wel.click();
        WebDriverWait wdw = new WebDriverWait(driver, timeout);
        wdw.until(ExpectedConditions.visibilityOfElementLocated(By.id(resultId)));
        wels = driver.findElements(By.name(tcName));
        if ((wels == null) || wels.isEmpty()) {
            throw new Exception("Test case " + tcName + " failed. No results after action link click.");
        }
    }

    return wels;
}