Java Code Examples for org.openqa.selenium.JavascriptExecutor

The following are top voted examples for showing how to use org.openqa.selenium.JavascriptExecutor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ats-framework   File: RealHtmlButton.java   Source Code and License 7 votes vote down vote up
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();
    }
 
Example 2
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   Source Code and License 7 votes vote down vote up
@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);
    }
}
 
Example 3
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   Source Code and License 7 votes vote down vote up
@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);
    }
}
 
Example 4
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 5
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 6
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 7
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 8
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 9
Project: LMSGrabber   File: PiazzaGrab.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 10
Project: syndesis-qe   File: CommonSteps.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 11
Project: NoraUi   File: Step.java   Source Code and License 6 votes vote down vote up
/**
 * 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 ...\"");
    }
}
 
Example 12
Project: ats-framework   File: HiddenHtmlTable.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 13
Project: ats-framework   File: HiddenHtmlTable.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: ats-framework   File: RealHtmlTable.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: ats-framework   File: RealHtmlElement.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 16
Project: POM_HYBRID_FRAMEOWRK   File: WebPage.java   Source Code and License 6 votes vote down vote up
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");
			}
		});
	}
 
Example 17
Project: testing_security_development_enterprise_systems   File: PageObject.java   Source Code and License 6 votes vote down vote up
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"));
}
 
Example 18
Project: testing_security_development_enterprise_systems   File: PageObject.java   Source Code and License 6 votes vote down vote up
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);
    });
}
 
Example 19
Project: opentest   File: ExecuteScript.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 20
Project: twitter-stuff   File: SeleniumPullingSearchScreen.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 21
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 22
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 23
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   Source Code and License 6 votes vote down vote up
@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);
    }

}
 
Example 24
Project: crawler   File: WindowUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 重新调整窗口大小,以适应页面,需要耗费一定时间。建议等待合理的时间。
 * @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();
}
 
Example 25
Project: teasy   File: AbstractSeleniumTest.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 26
Project: phoenix.webui.framework   File: SeleniumEngine.java   Source Code and License 5 votes vote down vote up
/**
 * 计算工具栏高度
 * @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;
}
 
Example 27
Project: phoenix.webui.framework   File: JsInvoker.java   Source Code and License 5 votes vote down vote up
/**
 * 执行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);
		}
	}
}
 
Example 28
Project: Selenium-Foundation   File: RobustJavascriptExecutor.java   Source Code and License 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example 29
Project: Selenium-Foundation   File: JsUtility.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
    }
}
 
Example 30
Project: Selenium-Foundation   File: WebDriverUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example 31
Project: Selenium-Foundation   File: ComponentContainerTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: Selenium-Foundation   File: JsUtilityTest.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 33
Project: Cognizant-Intelligent-Test-Scripter   File: CommonMethods.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 34
Project: NoraUi   File: Step.java   Source Code and License 5 votes vote down vote up
/**
 * 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());
    }

}
 
Example 35
Project: NoraUi   File: Auth.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }

}
 
Example 36
Project: NoraUi   File: BrowserSteps.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
    }
}
 
Example 37
Project: selenium-toys   File: SeleniumTests.java   Source Code and License 5 votes vote down vote up
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;
    }
  });
}
 
Example 38
Project: saladium   File: SaladiumDriver.java   Source Code and License 5 votes vote down vote up
@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!");
    }
}
 
Example 39
Project: AlipayAuto   File: AlipayAuto.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 40
Project: ats-framework   File: RealHtmlElement.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}