Java 类org.openqa.selenium.JavascriptExecutor 实例源码

项目:ats-framework    文件:RealHtmlButton.java   
private void doClick() {

        try {
            new RealHtmlElementState(this).waitToBecomeExisting();
            WebElement element = RealHtmlElementLocator.findElement(this);
            try {
                element.click();
            } catch (ElementNotVisibleException enve) {
                if (!UiEngineConfigurator.getInstance().isWorkWithInvisibleElements()) {
                    throw enve;
                }
                ((JavascriptExecutor) webDriver).executeScript("arguments[0].click()", element);
            }
        } catch (Exception e) {
            ((AbstractRealBrowserDriver) super.getUiDriver()).clearExpectedPopups();
            throw new SeleniumOperationException(this, "click", e);
        }

        UiEngineUtilities.sleep();

        ((AbstractRealBrowserDriver) super.getUiDriver()).handleExpectedPopups();
    }
项目:Cognizant-Intelligent-Test-Scripter    文件:JSCommands.java   
@Action(object = ObjectType.SELENIUM, desc = "Clear the element [<Object>]")
public void clearByJS() {
    if (elementPresent()) {
        try {
            JavascriptExecutor js = (JavascriptExecutor) Driver;
            js.executeScript("arguments[0].value=''", Element);
            Report.updateTestLog(Action, "Cleared value from '" + ObjectName + "'", Status.DONE);
        } catch (Exception ex) {
            Logger.getLogger(JSCommands.class.getName()).log(Level.SEVERE, null, ex);
            Report.updateTestLog(Action,
                    "Couldn't clear value on " + ObjectName + " - Exception " + ex.getMessage(), Status.FAIL);
        }
    } else {
        throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:JSCommands.java   
@Action(object = ObjectType.SELENIUM, desc = "Select element [<Object>] ", input = InputType.YES)
public void selectByJS() {
    if (elementPresent()) {
        try {
            JavascriptExecutor js = (JavascriptExecutor) Driver;
            Object value = js.executeScript(
                    "var options=arguments[0].getElementsByTagName('option');" + "for(var i=0;i<options.length;i++)"
                    + "{" + "var value=options[i].textContent?options[i].textContent:options[i].innerText;"
                    + "if(value.trim()==='" + Data.trim() + "')" + "{"
                    + "options[i].setAttribute('selected','selected');" + "return true;" + "}" + "}"
                    + "return false;",
                    Element);
            if (value != null && value.toString().trim().toLowerCase().equals("true")) {
                Report.updateTestLog(Action, "Item " + Data + " is selected from" + ObjectName, Status.DONE);
            } else {
                Report.updateTestLog(Action, "Item " + Data + " is not available in the" + ObjectName, Status.FAIL);
            }
        } catch (Exception ex) {
            Logger.getLogger(JSCommands.class.getName()).log(Level.SEVERE, null, ex);
            Report.updateTestLog(Action,
                    "Couldn't select value from " + ObjectName + " - Exception " + ex.getMessage(), Status.FAIL);
        }
    } else {
        throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
    }
}
项目:marathonv5    文件:JavaDriverTest.java   
public void executeScript() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        WebElement element1 = driver.findElement(By.name("text-field"));
        WebElement element2 = (WebElement) ((JavascriptExecutor) driver).executeScript("return $1;", element1);
        AssertJUnit.assertEquals(element1, element2);
    } finally {
        JavaElementFactory.reset();
    }
}
项目:marathonv5    文件:JavaDriverTest.java   
public void executeScriptWithPrimitiveReturn() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        WebElement element1 = driver.findElement(By.name("text-field"));
        Number width = (Number) ((JavascriptExecutor) driver).executeScript("return Double.valueOf($1.getSize().getWidth());",
                element1);
        AssertJUnit.assertTrue(width.doubleValue() > 0);
    } finally {
        JavaElementFactory.reset();
    }
}
项目:marathonv5    文件:JavaDriverTest.java   
public void executeAsyncScript() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        WebElement element1 = driver.findElement(By.name("text-field"));
        WebElement element2 = (WebElement) ((JavascriptExecutor) driver).executeAsyncScript("$2.call($1);", element1);
        AssertJUnit.assertEquals(element1, element2);
    } finally {
        JavaElementFactory.reset();
    }
}
项目:marathonv5    文件:JavaDriverTest.java   
public void executeAsyncScriptWithoutCallback() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        WebElement element1 = driver.findElement(By.name("text-field"));
        ((JavascriptExecutor) driver).executeAsyncScript("$1.setText(\"hello world\");", element1);
        throw new MissingException(WebDriverException.class);
    } catch (WebDriverException e) {
    } finally {
        JavaElementFactory.reset();
    }
}
项目:marathonv5    文件:JavaDriverTest.java   
public void executeAsyncScriptWithNullReturn() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        WebElement element1 = driver.findElement(By.name("text-field"));
        WebElement element2 = (WebElement) ((JavascriptExecutor) driver).executeAsyncScript("$2.call(null);", element1);
        AssertJUnit.assertNull(element2);
    } finally {
        JavaElementFactory.reset();
    }
}
项目:LMSGrabber    文件:PiazzaGrab.java   
@Override
public void getCourseListings() throws MalformedURLException {
  // From the home page, retrieve all links to current courses
  List<WebElement> links = action.driver.findElements(By.xpath("//*[@data-pats='classes_dropdown_item']"));
  System.out.println(links.size());//*[@id="network_j6feqds1z771k1"]/
  //*[@id="network_j6feqds1z771k1"]/div
  CourseListing[] cls = new CourseListing[links.size()];
  for (int i = 0; i < links.size(); i++) {
    cls[i] = new CourseListing();
    String script = "return arguments[0].innerText";
    cls[i].course_name  = (String) ((JavascriptExecutor) action.driver).executeScript(script, links.get(i));
    String course_url = baseurl + "/class/" + links.get(i).getAttribute("id").replace("network_", "");
    cls[i].base_url = course_url;
    System.out.println(cls[i].base_url + "**************");
  }
  addSubGrabber(cls);
}
项目:syndesis-qe    文件:CommonSteps.java   
/**
 * Scroll the webpage.
 *
 * @param topBottom possible values: top, bottom
 * @param leftRight possible values: left, right
 * @returns {Promise<any>}
 */
@When("^scroll \"([^\"]*)\" \"([^\"]*)\"$")
public void scrollTo(String topBottom, String leftRight) {
    WebDriver driver = WebDriverRunner.getWebDriver();
    JavascriptExecutor jse = (JavascriptExecutor) driver;

    int x = 0;
    int y = 0;

    Long width = (Long) jse.executeScript("return $(document).width()");
    Long height = (Long) jse.executeScript("return $(document).height()");

    if (leftRight.equals("right")) {
        y = width.intValue();
    }

    if (topBottom.equals("bottom")) {
        x = height.intValue();
    }

    jse.executeScript("(browserX, browserY) => window.scrollTo(browserX, browserY)", x, y);
}
项目:NoraUi    文件:Step.java   
/**
 * Update a html input text with a text.
 *
 * @param pageElement
 *            Is target element
 * @param textOrKey
 *            Is the new data (text or text in context (after a save))
 * @param keysToSend
 *            character to send to the element after {@link org.openqa.selenium.WebElement#sendKeys(CharSequence...) sendKeys} with textOrKey
 * @param args
 *            list of arguments to format the found selector with
 * @throws TechnicalException
 *             is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_ERROR_ON_INPUT} message (with screenshot, no exception)
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
protected void updateText(PageElement pageElement, String textOrKey, CharSequence keysToSend, Object... args) throws TechnicalException, FailureException {
    String value = Context.getValue(textOrKey) != null ? Context.getValue(textOrKey) : textOrKey;
    if (!"".equals(value)) {
        try {
            WebElement element = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(pageElement, args)));
            element.clear();
            if (DriverFactory.IE.equals(Context.getBrowser())) {
                String javascript = "arguments[0].value='" + value + "';";
                ((JavascriptExecutor) getDriver()).executeScript(javascript, element);
            } else {
                element.sendKeys(value);
            }
            if (keysToSend != null) {
                element.sendKeys(keysToSend);
            }
        } catch (Exception e) {
            new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_ERROR_ON_INPUT), pageElement, pageElement.getPage().getApplication()), true,
                    pageElement.getPage().getCallBack());
        }
    } else {
        logger.debug("Empty data provided. No need to update text. If you want clear data, you need use: \"I clear text in ...\"");
    }
}
项目:ats-framework    文件:HiddenHtmlTable.java   
/**
 * Set value of specified table field
 *
 * @param value the new table cell value
 * @param row the field row starting at 0
 * @param column the field column starting at 0
 */
@Override
@PublicAtsApi
public void setFieldValue( String value, int row, int column ) {

    new HiddenHtmlElementState(this).waitToBecomeExisting();

    WebElement table = HiddenHtmlElementLocator.findElement(this);

    String script = "var table = arguments[0]; var row = arguments[1]; var col = arguments[2];"
                    + "if (row > table.rows.length) { return \"Cannot access row \" + row + \" - table has \" + table.rows.length + \" rows\"; }"
                    + "if (col > table.rows[row].cells.length) { return \"Cannot access column \" + col + \" - table row has \" + table.rows[row].cells.length + \" columns\"; }"
                    + "table.rows[row].cells[col].textContent = '" + value + "';";

    ((JavascriptExecutor) webDriver).executeScript(script, table, row, column);
}
项目:ats-framework    文件:HiddenHtmlTable.java   
/**
 * Get the value of the specified table field
 *
 * @param row the field row starting at 0
 * @param column the field column starting at 0
 * @return the value
 */
@Override
@PublicAtsApi
public String getFieldValue( int row, int column ) {

    new HiddenHtmlElementState(this).waitToBecomeExisting();

    WebElement table = HiddenHtmlElementLocator.findElement(this);
    String script = "var table = arguments[0]; var row = arguments[1]; var col = arguments[2];"
                    + "if (row > table.rows.length) { return \"Cannot access row \" + row + \" - table has \" + table.rows.length + \" rows\"; }"
                    + "if (col > table.rows[row].cells.length) { return \"Cannot access column \" + col + \" - table row has \" + table.rows[row].cells.length + \" columns\"; }"
                    + "return table.rows[row].cells[col];";

    JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver;
    Object value = jsExecutor.executeScript(script, table, row, column);
    if (value instanceof WebElement) {

        return ((WebElement) value).getText().trim();
    }
    return null;
}
项目:ats-framework    文件:RealHtmlTable.java   
/**
 * Get the value of the specified table field
 *
 * @param row the field row starting at 0
 * @param column the field column starting at 0
 * @return
 */
@Override
@PublicAtsApi
public String getFieldValue( int row, int column ) {

    new RealHtmlElementState(this).waitToBecomeExisting();

    WebElement table = RealHtmlElementLocator.findElement(this);

    String script = "var table = arguments[0]; var row = arguments[1]; var col = arguments[2];"
                    + "if (row > table.rows.length) { return \"Cannot access row \" + row + \" - table has \" + table.rows.length + \" rows\"; }"
                    + "if (col > table.rows[row].cells.length) { return \"Cannot access column \" + col + \" - table row has \" + table.rows[row].cells.length + \" columns\"; }"
                    + "return table.rows[row].cells[col];";

    Object value = ((JavascriptExecutor) webDriver).executeScript(script, table, row, column);
    if (value instanceof WebElement) {
        return ((WebElement) value).getText().trim();
    }
    return null;
}
项目:ats-framework    文件:RealHtmlElement.java   
/**
 * Simulate mouse click action
 */
@Override
@PublicAtsApi
public void click() {

    new RealHtmlElementState(this).waitToBecomeExisting();

    try {
        WebElement element = RealHtmlElementLocator.findElement(this);
        try {
            element.click();
        } catch (ElementNotInteractableException enie) {
            if (!UiEngineConfigurator.getInstance().isWorkWithInvisibleElements()) {
                throw enie;
            }
            ((JavascriptExecutor) webDriver).executeScript("arguments[0].click()", element);
        }
    } catch (Exception e) {
        throw new SeleniumOperationException(this, "click", e);
    }
}
项目:POM_HYBRID_FRAMEOWRK    文件:WebPage.java   
public static void waitForPageLoad(WebDriver driver) {

        Wait<WebDriver> wait = new WebDriverWait(driver, 30);
        wait.until(new Function<WebDriver, Boolean>() {

            /* (non-Javadoc)
             * @see java.util.function.Function#apply(java.lang.Object)
             */
            public Boolean apply(WebDriver driver_) {
                System.out.println("Current Window State       : "
                        + String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")));
                return String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))
                        .equals("complete");
            }
        });
    }
项目:testing_security_development_enterprise_systems    文件:PageObject.java   
protected Boolean waitForPageToLoad() {
    WebDriverWait wait = new WebDriverWait(driver, 10); //give up after 10 seconds

    //keep executing the given JS till it returns "true", when page is fully loaded and ready
    return wait.until((ExpectedCondition<Boolean>) input -> (
            (JavascriptExecutor) input).executeScript("return document.readyState").equals("complete"));
}
项目:testing_security_development_enterprise_systems    文件:PageObject.java   
protected Boolean waitForPageToLoad() {
    JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
    WebDriverWait wait = new WebDriverWait(driver, 10); //give up after 10 seconds

    //keep executing the given JS till it returns "true", when page is fully loaded and ready
    return wait.until((ExpectedCondition<Boolean>) input -> {
        String res = jsExecutor.executeScript("return /loaded|complete/.test(document.readyState);").toString();
        return Boolean.parseBoolean(res);
    });
}
项目:opentest    文件:ExecuteScript.java   
@Override
public void run() {
    super.run();

    String script = this.readStringArgument("script");
    Boolean async = this.readBooleanArgument("async", false);
    Integer timeoutSec = this.readIntArgument("timeoutSec", 20);

    this.waitForAsyncCallsToFinish();

    driver.manage().timeouts().setScriptTimeout(timeoutSec, TimeUnit.SECONDS);  
    JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
    if (async) {
        jsExecutor.executeAsyncScript(script);
    } else {
        jsExecutor.executeScript(script);
    }
}
项目:twitter-stuff    文件:SeleniumPullingSearchScreen.java   
private static void parseTweets(WebDriver driver, Set<String> itemIds, String url) {
    driver.get(url);
    boolean canScroll;
    do {
        JavascriptExecutor js = ((JavascriptExecutor) driver);
        js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

        List<WebElement> webElements = driver.findElements(By.cssSelector(".has-more-items"));
        canScroll = (webElements.size() > 0);
    } while (canScroll);

    List<WebElement> tweetElements =
            driver.findElements(By.cssSelector(".js-stream-item.stream-item.stream-item"));
    for (WebElement tweetElement : tweetElements) {
        String itemId = tweetElement.getAttribute("data-item-id");
        itemIds.add(itemId);
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:JSCommands.java   
@Action(object = ObjectType.SELENIUM, desc = "Click on [<Object>]")
public void clickByJS() {
    if (elementPresent()) {
        try {
            JavascriptExecutor js = (JavascriptExecutor) Driver;
            js.executeScript("arguments[0].click();", Element);
            Report.updateTestLog(Action, "Clicked on " + ObjectName, Status.DONE);
        } catch (Exception ex) {
            Logger.getLogger(JSCommands.class.getName()).log(Level.SEVERE, null, ex);
            Report.updateTestLog(Action, "Couldn't click on " + ObjectName + " - Exception " + ex.getMessage(),
                    Status.FAIL);
        }
    } else {
        throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:JSCommands.java   
@Action(object = ObjectType.SELENIUM, desc = "Set [<Data>] on [<Object>]", input = InputType.YES)
public void setByJS() {
    if (elementPresent()) {
        try {
            JavascriptExecutor js = (JavascriptExecutor) Driver;
            js.executeScript("arguments[0].value='" + Data + "'", Element);
            Report.updateTestLog(Action, "Entered Text '" + Data + "' on '" + ObjectName + "'", Status.DONE);
        } catch (Exception ex) {
            Logger.getLogger(JSCommands.class.getName()).log(Level.SEVERE, null, ex);
            Report.updateTestLog(Action, "Couldn't set value on " + ObjectName + " - Exception " + ex.getMessage(),
                    Status.FAIL);
        }
    } else {
        throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:JSCommands.java   
@Action(object = ObjectType.SELENIUM, desc = "To check if [<Object>] is inside the boundary ")
public void assertInsideBounds() {
    if (elementPresent()) {
        JavascriptExecutor js = (JavascriptExecutor) Driver;
        Object value = js.executeScript("" + "return isOutside(arguments[0]);" + "function isOutside(x){"
                + "     return x.scrollWidth <= x.offsetWidth;" + "}", Element);
        if (value != null && Boolean.valueOf(value.toString())) {
            Report.updateTestLog(Action, "Element " + ObjectName + " is inside bounds", Status.PASS);
        } else {
            Report.updateTestLog(Action, "Element " + ObjectName + " is outside bounds", Status.FAIL);
        }
    } else {
        throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
    }

}
项目:crawler    文件:WindowUtil.java   
/**
 * 重新调整窗口大小,以适应页面,需要耗费一定时间。建议等待合理的时间。
 * @param driver
 */
public static void loadAll(WebDriver driver){
    Dimension od=driver.manage().window().getSize();
    int width=driver.manage().window().getSize().width;
    //尝试性解决:https://github.com/ariya/phantomjs/issues/11526问题
       driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); 
    long height=(Long)((JavascriptExecutor)driver).executeScript("return document.body.scrollHeight;");
    driver.manage().window().setSize(new Dimension(width, (int)height));
    driver.navigate().refresh();
}
项目:teasy    文件:AbstractSeleniumTest.java   
@AfterMethod(alwaysRun = true)
public void doAfterMethods() {
    //TODO VE: sometimes local data may be needed so it's worth to make it optional/configurable
    cookiesService.deleteAllCookies();
    try {
        ((JavascriptExecutor) getWebDriver()).executeScript("window.localStorage.clear();");
        ((JavascriptExecutor) getWebDriver()).executeScript("window.sessionStorage.clear();");
    } catch (Exception ignored) {
    }
    methodsInvoker.invokeMethodsByAnnotation(this, OurAfterMethod.class);
}
项目:phoenix.webui.framework    文件:SeleniumEngine.java   
/**
 * 计算工具栏高度
 * @return 高度
 */
public int computeToolbarHeight()
{
    JavascriptExecutor jsExe = (JavascriptExecutor) driver;
    Object objectHeight = jsExe.executeScript("return window.outerHeight - window.innerHeight;");
    if(objectHeight instanceof Long)
    {
        toolbarHeight = ((Long) objectHeight).intValue();
    }

    return toolbarHeight;
}
项目:phoenix.webui.framework    文件:JsInvoker.java   
/**
 * 执行js代码
 * @param util 框架默认提供的参数
 * @param params 要执行的js代码,如果有多个的话,将会顺序执行
 */
public static void execute(Phoenix util, String[] params)
{
    WebDriver driver = util.getEngine().getDriver();
    JavascriptExecutor jsDriver = (JavascriptExecutor) driver;

    if(params != null)
    {
        for(String param : params)
        {
            jsDriver.executeScript(param);
        }
    }
}
项目:Selenium-Foundation    文件:RobustJavascriptExecutor.java   
/**
 * Constructor for robust JavaScript executor
 * 
 * @param driver driver object
 */
public RobustJavascriptExecutor(WebDriver driver) {
    if (driver instanceof JavascriptExecutor) {
        executor = (JavascriptExecutor) driver;
    } else {
        throw new UnsupportedOperationException("The specified driver is unable to execute JavaScript");
    }
}
项目:Selenium-Foundation    文件:JsUtility.java   
/**
 * Inject the Java glue code library into the current window
 * 
 * @param driver A handle to the currently running Selenium test window.
 */
public static void injectGlueLib(WebDriver driver) {
    JavascriptExecutor executor = WebDriverUtils.getExecutor(driver);
    if ((boolean) executor.executeScript("return (typeof isObject != 'function');")) {
        executor.executeScript(getScriptResource(JsUtility.JAVA_GLUE_LIB));
    }
}
项目:Selenium-Foundation    文件:WebDriverUtils.java   
/**
 * Get a JavaScript code executor for the specified search context
 * 
 * @param context search context
 * @return context-specific {@link JavascriptExecutor}
 */
public static JavascriptExecutor getExecutor(SearchContext context) {
    WebDriver driver = getDriver(context);
    if (driver instanceof JavascriptExecutor) {
        return new RobustJavascriptExecutor(driver);
    } else {
        throw new UnsupportedOperationException("The specified context is unable to execute JavaScript");
    }
}
项目:Selenium-Foundation    文件:ComponentContainerTest.java   
/**
 * Create mocked {@link WebDriver} object.
 * 
 * @return mocked WebDriver object
 */
private static WebDriver mockDriver() {
    WebDriver driver = mock(WebDriver.class, withSettings().extraInterfaces(JavascriptExecutor.class));
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    when(executor.executeScript(any(String.class), anyVararg())).thenReturn(null);
    return driver;
}
项目:Selenium-Foundation    文件:JsUtilityTest.java   
@Test
public void testInjectGlueLib() {
    ExamplePage page = getPage();
    WebDriver driver = page.getDriver();
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    JsUtility.injectGlueLib(page.getDriver());
    Boolean hasFunction = (Boolean) executor.executeScript("return (typeof isObject == 'function');");
    assertTrue(hasFunction);
}
项目:Cognizant-Intelligent-Test-Scripter    文件:CommonMethods.java   
@Action(object = ObjectType.BROWSER, desc = "Store the result of Javascript expression value in a variable", input = InputType.YES, condition = InputType.YES)
public void storeEval() {
    String javaScript = Data;
    String variableName = Condition;
    if (variableName.matches("%.*%")) {
        JavascriptExecutor js = (JavascriptExecutor) Driver;
        addVar(variableName, js.executeScript(javaScript).toString());
        Report.updateTestLog(Action, "Eval Stored", Status.DONE);
    } else {
        Report.updateTestLog(Action, "Variable format is not correct", Status.FAIL);
    }
}
项目:NoraUi    文件:Step.java   
/**
 * Passes over a specific page element triggering 'mouseover' js event.
 *
 * @param element
 *            Target page element
 * @throws TechnicalException
 *             is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Failure with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_PASS_OVER_ELEMENT} message (with screenshot)
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
protected void passOver(PageElement element) throws TechnicalException, FailureException {
    try {
        String javascript = "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);";
        ((JavascriptExecutor) getDriver()).executeScript(javascript, Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(element))));

    } catch (Exception e) {
        new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_PASS_OVER_ELEMENT), element, element.getPage().getApplication()), true,
                element.getPage().getCallBack());
    }

}
项目:NoraUi    文件:Auth.java   
/**
 * Loads authentication cookie in the current web browsers. The way is different for phantomjs.
 *
 * @param browser
 *            the name of the current browser
 */
public static void loadAuthentication(String browser) {
    if (DriverFactory.PHANTOM.equals(browser)) {
        JavascriptExecutor js = (JavascriptExecutor) Context.getDriver();
        js.executeScript("document.cookie = \"" + getInstance().authCookie.getName() + "=" + getInstance().authCookie.getValue() + ";path=" + getInstance().authCookie.getPath() + ";domain="
                + getInstance().authCookie.getDomain() + "\"");
    } else {
        Context.getDriver().manage().addCookie(getInstance().authCookie);
    }

}
项目:NoraUi    文件:BrowserSteps.java   
/**
 * Open new window with conditions.
 * Note: after this action, you need use "Given '.....' is opened."
 * {@link com.github.noraui.browser.steps.BrowserSteps#openUrlIfDifferent(String, List) openUrlIfDifferent}
 *
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
@Conditioned
@Quand("J'ouvre une nouvelle fenêtre[\\.|\\?]")
@When("I open a new window[\\.|\\?]")
public void openNewWindow(List<GherkinStepCondition> conditions) throws FailureException {
    try {
        Set<String> initialWindows = Context.getDriver().getWindowHandles();
        String js = "window.open(\"\");";
        ((JavascriptExecutor) Context.getDriver()).executeScript(js);
        String newWindowHandle = Context.waitUntil(WindowManager.newWindowOpens(initialWindows));
        Context.getDriver().switchTo().window(newWindowHandle);
    } catch (Exception e) {
        new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_OPEN_A_NEW_WINDOW), true, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
    }
}
项目:selenium-toys    文件:SeleniumTests.java   
private void waitForDocumentReady() {
  final WebDriverWait wait = new WebDriverWait(webDriver, 30);

  wait.until((ExpectedCondition<Boolean>) driver -> ((JavascriptExecutor) driver)
      .executeScript("return document.readyState").equals("complete"));
  wait.until((ExpectedCondition<Boolean>) driver -> {
    try {
      return ((Long) ((JavascriptExecutor) driver).executeScript("return jQuery.active") == 0);
    } catch (Exception e) {
      // no jQuery present
      return true;
    }
  });
}
项目:saladium    文件:SaladiumDriver.java   
@Override
public void html5Erreur(String selector) {
    this.logger.debug("Appel du test messageErreur()");
    JavascriptExecutor js = this;
    Boolean s = (Boolean) js.executeScript("return document.querySelector('"
        + selector + "').validity.valid");
    if (!s) {
        Assert.fail(selector + " " + s
            + " Un message de sevérité ERROR devrait être présent!");
    }
}
项目:AlipayAuto    文件:AlipayAuto.java   
private static String getOppositeUser(String transactionNo) {
    // ��ȡ�ؼ��ֶ�Ӧ��������
    WebElement keywordInput = driver.findElement(By.id("J-keyword"));
    keywordInput.clear();
    keywordInput.sendKeys(transactionNo);
    WebElement keywordSelect = driver.findElement(By.id("keyword"));
    List<WebElement> options = keywordSelect.findElements(By.tagName("option"));
    // until������ʾֱ���ɵ��ٵ�
    // WebElement selectElement = wait.until(ExpectedConditions
    // .visibilityOfElementLocated(By.id("keyword")));
    // ��Ҫִ��JavaScript��䣬����ǿתdriver
    JavascriptExecutor js = (JavascriptExecutor) driver;
    // Ҳ������ô��setAttribute("style","");
    js.executeScript("document.getElementById('keyword').style.display='list-item';");
    js.executeScript("document.getElementById('keyword').removeAttribute('smartracker');");
    js.executeScript("document.getElementById('keyword').options[1].selected = true;");
    js.executeScript("document.getElementById('J-select-range').style.display='list-item';");
    // ���ý���ʱ��ѡ��
    Select selectTime = new Select(driver.findElement(By.id("J-select-range")));
    selectTime.selectByIndex(3);// ѡ�е������������
    System.out.println("selectTime.isMultiple() : " + selectTime.isMultiple());
    // ���ùؼ���ѡ��
    Select selectKeyword = new Select(driver.findElement(By.id("keyword")));
    // selectKeyword.selectByValue("bizInNo");//�˴���value��д<option>��ǩ�е�valueֵ
    selectKeyword.selectByIndex(1);// ѡ�е��ǽ��׺�
    System.out.println("selectKeyword.isMultiple() : " + selectKeyword.isMultiple());
    WebElement queryButton = driver.findElement(By.id("J-set-query-form"));// �õ�������ť
    // ���������ť
    queryButton.submit();
    WebElement tr = driver.findElement(By.id("J-item-1"));// �Ȼ�ȡtr
    WebElement td = tr.findElement(By.xpath("//*[@id=\"J-item-1\"]/td[5]/p[1]"));
    return td.getText();
}
项目:ats-framework    文件:RealHtmlElement.java   
/**
 * Scroll to this element, so it is viewable.
 * Should be used when working in large pages where scrolling is possible and needed.
 */
@PublicAtsApi
public void scrollTo() {

    new RealHtmlElementState(this).waitToBecomeExisting();

    WebElement element = RealHtmlElementLocator.findElement(this);
    ((JavascriptExecutor) webDriver).executeScript("arguments[0].scrollIntoView();", element);
}