Java Code Examples for org.openqa.selenium.JavascriptExecutor#executeScript()

The following examples show how to use org.openqa.selenium.JavascriptExecutor#executeScript() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScrollbarHandler.java    From vividus with Apache License 2.0 6 votes vote down vote up
private <T> T performWithHiddenScrollabrs(Supplier<T> action, WebElement scrollableElement)
{
    String parameter = scrollableElement == null ? "document.documentElement" : "arguments[0]";
    if (webDriverManager.isMobile())
    {
        return action.get();
    }
    Object originalStyleOverflow = null;
    JavascriptExecutor executor = (JavascriptExecutor) webDriverProvider.get();
    try
    {
        originalStyleOverflow = executor.executeScript(String.format(
                "var originalStyleOverflow = %1$s.style.overflow;"
              + "%1$s.style.overflow='hidden';"
              + "return originalStyleOverflow;", parameter), scrollableElement);
        return action.get();
    }
    finally
    {
        if (null != originalStyleOverflow)
        {
            executor.executeScript(parameter + ".style.overflow=arguments[1];", scrollableElement,
                    originalStyleOverflow);
        }
    }
}
 
Example 2
Source File: InstructorStudentListPage.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
public void verifyProfilePhoto(String courseId, String studentName, String urlRegex) {
    String rowId = getStudentRowId(courseId, studentName);
    verifyImageUrl(urlRegex, browser.driver
            .findElement(By.id("studentphoto-c" + rowId))
            .findElement(By.tagName("img"))
            .getAttribute("src"));
    WebElement photo = browser.driver.findElement(By.id("studentphoto-c" + rowId))
                                     .findElement(By.cssSelector(".profile-pic-icon-click > img"));
    JavascriptExecutor jsExecutor = (JavascriptExecutor) browser.driver;
    jsExecutor.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -100);", photo);
    Actions action = new Actions(browser.driver);
    action.click(photo).build().perform();
    verifyImageUrl(urlRegex, browser.driver
            .findElement(By.id("studentphoto-c" + rowId))
            .findElement(By.cssSelector(".popover-content > .profile-pic"))
            .getAttribute("src"));
}
 
Example 3
Source File: JsInvoker.java    From phoenix.webui.framework with Apache License 2.0 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 4
Source File: AbstractMultipleSelect2.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected BiFunction<WebElement, R, Boolean> deselect() {
    return (selected, value) -> {
        WebElement selection = selected.findElements(By.tagName("div")).get(0);
        if (identity().apply(value).equals(selection.getText())) {
            WebElement element = selected.findElement(By.xpath(".//a[contains(@class,'select2-search-choice-close')]"));
            JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("arguments[0].click();", element);
            pause(500);
            return true;
        }
        return false;
    };
}
 
Example 5
Source File: TestTools.java    From site-infrastructure-tests with Apache License 2.0 5 votes vote down vote up
public static void assertToolVersionIsOrLater(WebDriver driver, String script, String minVersion) {
	if (logger.isDebugEnabled()) {
		logger.debug("assert version '{}' >= '{}'", script, minVersion);
	}
	JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
	Object response = jsExecutor.executeScript(script);
	// make sure the element exists
	if (String.class.isAssignableFrom(response.getClass())) {
		boolean result = Tools.testVersionNotOlderThanBaseVersion((String) response, minVersion);
		Assert.assertEquals(true, result);
	} else {
		Assert.fail();
	}
}
 
Example 6
Source File: ITCreateDuplicateBucket.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    // bucket cleanup

    // confirm all buckets checkbox exists
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#nifi-registry-workflow-administration-buckets-list-container-column-header div.mat-checkbox-inner-container")));

    // select all buckets checkbox
    WebElement selectAllCheckbox = driver.findElement(By.cssSelector("#nifi-registry-workflow-administration-buckets-list-container-column-header div.mat-checkbox-inner-container"));
    selectAllCheckbox.click();

    // confirm actions drop down menu exists
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#nifi-registry-workflow-administration-perspective-buckets-container button.mat-fds-primary")));

    // select actions drop down
    WebElement selectActions = driver.findElement(By.cssSelector("#nifi-registry-workflow-administration-perspective-buckets-container button.mat-fds-primary"));
    selectActions.click();

    // select delete
    WebElement selectDeleteBucket = driver.findElement(By.cssSelector("div.mat-menu-content button.mat-menu-item"));
    JavascriptExecutor executor = (JavascriptExecutor)driver;
    executor.executeScript("arguments[0].click();", selectDeleteBucket);

    // verify bucket deleted
    WebElement confirmDelete = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.fds-dialog-actions button.mat-fds-warn")));
    confirmDelete.click();
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-automation-id='no-buckets-message']")));

    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
        fail(verificationErrorString);
    }
}
 
Example 7
Source File: WebElementHighlighter.java    From Selenium with The Unlicense 5 votes vote down vote up
public void highlightElement(WebDriver driver, WebElement element) { 
for (int i = 0; i < 1; i++) { 
	JavascriptExecutor js = (JavascriptExecutor)driver;
	 js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: black; border: 3px solid black;"); 
	 
	 }
}
 
Example 8
Source File: AdfConditions.java    From adf-selenium with Apache License 2.0 5 votes vote down vote up
public static ExpectedCondition<Boolean> javascriptExpressionTrue(final String jsExpression, final Object... args) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(final WebDriver driver) {
            JavascriptExecutor jsDriver = (JavascriptExecutor) driver;
            logger.log(Level.FINER, "executing condition javascript: {0}", jsExpression);
            Object result = jsDriver.executeScript(jsExpression, args);
            logger.log(Level.FINER, "js result: {0}", result);
            return Boolean.TRUE.equals(result);
        }
    };
}
 
Example 9
Source File: TestTools.java    From site-infrastructure-tests with Apache License 2.0 5 votes vote down vote up
public static void assertToolVersionIsBelow(WebDriver driver, String script, String maxVersion) {
	if (logger.isDebugEnabled()) {
		logger.debug("assert version '{}' < '{}'", script, maxVersion);
	}
	JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
	Object response = jsExecutor.executeScript(script);
	// make sure the element exists
	if (String.class.isAssignableFrom(response.getClass())) {
		boolean result = Tools.testVersionIsOlderThanBaseVersion((String) response, maxVersion);
		Assert.assertEquals(true, result);
	} else {
		Assert.fail();
	}
}
 
Example 10
Source File: Element.java    From JTAF-ExtWebDriver with Apache License 2.0 5 votes vote down vote up
/***
 * Determine if the element is within the bounds of the window
 * 
 * @return true or false
 * @throws WidgetException
 */
public boolean isWithinBoundsOfWindow() throws WidgetException {
	
	JavascriptExecutor js = ((JavascriptExecutor) getGUIDriver().getWrappedDriver());
	
	// execute javascript to get scroll values
	Object top = js.executeScript("return document.body.scrollTop;");
	Object left = js.executeScript("return document.body.scrollLeft;");
	
	int scrollTop;
	int scrollLeft;
	try {
		scrollTop = Integer.parseInt(top+"");
		scrollLeft = Integer.parseInt(left+"");
	}
	catch(NumberFormatException e) {
		throw new WidgetException("There was an error parsing the scroll values from the page", getByLocator());
	}
	
	// calculate bounds
	Dimension dim = getGUIDriver().getWrappedDriver().manage().window().getSize();
	int windowWidth = dim.getWidth();
	int windowHeight = dim.getHeight();
	int x = ((Locatable)getWebElement()).getCoordinates().onPage().getX();
	int y = ((Locatable)getWebElement()).getCoordinates().onPage().getY();
	int relX = x - scrollLeft;
	int relY = y - scrollTop;
	return relX + findElement().getSize().getWidth() <= windowWidth && 
			relY + findElement().getSize().getHeight() <= windowHeight && 
				relX >= 0 && relY >= 0;
}
 
Example 11
Source File: JSPolicyForm.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void populate(JSPolicyRepresentation expected, boolean save) {
    UIUtils.setTextInputValue(name, expected.getName());
    UIUtils.setTextInputValue(description, expected.getDescription());
    logic.selectByValue(expected.getLogic().name());

    JavascriptExecutor scriptExecutor = (JavascriptExecutor) driver;

    scriptExecutor.executeScript("angular.element(document.getElementById('code')).scope().policy.code = '" + expected.getCode() + "'");

    if (save) {
        save();
    }
}
 
Example 12
Source File: ITRenameBucket.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    // wait for side nav to close
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("mat-sidenav")));

    // bucket cleanup

    // confirm all buckets checkbox exists
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#nifi-registry-workflow-administration-buckets-list-container-column-header div.mat-checkbox-inner-container")));

    // select all buckets checkbox
    WebElement selectAllCheckbox = driver.findElement(By.cssSelector("#nifi-registry-workflow-administration-buckets-list-container-column-header div.mat-checkbox-inner-container"));
    selectAllCheckbox.click();

    // confirm actions drop down menu exists
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#nifi-registry-workflow-administration-perspective-buckets-container button.mat-fds-primary")));

    // select actions drop down
    WebElement selectActions = driver.findElement(By.cssSelector("#nifi-registry-workflow-administration-perspective-buckets-container button.mat-fds-primary"));
    selectActions.click();

    // select delete
    WebElement selectDeleteBucket = driver.findElement(By.cssSelector("div.mat-menu-content button.mat-menu-item"));
    JavascriptExecutor executor = (JavascriptExecutor)driver;
    executor.executeScript("arguments[0].click();", selectDeleteBucket);

    // verify bucket deleted
    WebElement confirmDelete = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.fds-dialog-actions button.mat-fds-warn")));
    confirmDelete.click();
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-automation-id='no-buckets-message']")));

    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
        fail(verificationErrorString);
    }
}
 
Example 13
Source File: JsUtility.java    From Selenium-Foundation with Apache License 2.0 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(final WebDriver driver) {
    JavascriptExecutor executor = WebDriverUtils.getExecutor(driver);
    if ((boolean) executor.executeScript("return (typeof isObject != 'function');")) {
        executor.executeScript(getScriptResource(JsUtility.JAVA_GLUE_LIB));
    }
}
 
Example 14
Source File: SelfHealingEngineTest.java    From healenium-web with Apache License 2.0 5 votes vote down vote up
@Test
public void locatorHealingTest() {
    final By inputFieldLocator = By.xpath("//input[@name='source']");
    driver.get("https://google.com/");
    PageAwareBy by = PageAwareBy.by(PAGE_NAME, inputFieldLocator);
    WebElement input = driver.findElement(by);
    JavascriptExecutor js = driver.getDelegate();
    js.executeScript("arguments[0].setAttribute('name', 'source_new')", input);
    by = PageAwareBy.by(PAGE_NAME, inputFieldLocator);
    input = driver.findElement(by);
    By newLocation = driver.getCurrentEngine().findNewLocations(by, driver.getPageSource()).get(0).getValue();
    Assertions.assertEquals(input, driver.findElement(newLocation));
}
 
Example 15
Source File: ImageCommand.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public void pageDownBrowser(int dh) {
    if (isHeadless()) {
        SCREEN.type(Key.PAGE_DOWN);
    } else {
        dh = Math.max(0, dh);
        JavascriptExecutor jse = ((JavascriptExecutor) Driver);
        jse.executeScript(String.format("window.scrollBy(0, window.innerHeight-%s)", dh));
    }
}
 
Example 16
Source File: ClosureTestStatement.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public void evaluate() throws Throwable {
  URL testUrl = filePathToUrlFn.apply(testPath);
  LOG.info("Running: " + testUrl);

  Stopwatch stopwatch = Stopwatch.createStarted();

  WebDriver driver = driverSupplier.get();

  if (!isOnTravis()) {
    // Attempt to make the window as big as possible.
    try {
      driver.manage().window().maximize();
    } catch (RuntimeException ignored) {
      // We tried.
    }
  }

  JavascriptExecutor executor = (JavascriptExecutor) driver;
  // Avoid Safari JS leak between tests.
  executor.executeScript("if (window && window.top) window.top.G_testRunner = null");

  try {
    driver.get(testUrl.toString());
  } catch (WebDriverException e) {
    fail("Test failed to load: " + e.getMessage());
  }

  while (!getBoolean(executor, Query.IS_FINISHED)) {
    long elapsedTime = stopwatch.elapsed(TimeUnit.SECONDS);
    if (timeoutSeconds > 0 && elapsedTime > timeoutSeconds) {
      throw new JavaScriptAssertionError("Tests timed out after " + elapsedTime + " s. \nCaptured Errors: " +
                                         ((JavascriptExecutor) driver).executeScript("return window.errors;")
                                         + "\nPageSource: " + driver.getPageSource() + "\nScreenshot: " +
                                         ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64));
    }
    TimeUnit.MILLISECONDS.sleep(100);
  }

  if (!getBoolean(executor, Query.IS_SUCCESS)) {
    String report = getString(executor, Query.GET_REPORT);
    throw new JavaScriptAssertionError(report);
  }
}
 
Example 17
Source File: SeleniumJavaScriptClickLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
private void clickElement(WebElement element) {
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element);
}
 
Example 18
Source File: Commons.java    From qa-automation-samples with MIT License 4 votes vote down vote up
public static void swipeInvertiOS() {
    JavascriptExecutor js = (JavascriptExecutor) DriverFactoryManager.getDriver();
    HashMap<String, String> scrollObject = new HashMap<String, String>();
    scrollObject.put("direction", "down");
    js.executeScript("mobile: swipe", scrollObject);
}
 
Example 19
Source File: HtmlFileBrowse.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
*
* @param webDriver {@link WebDriver} instance
* @param value the file input value to set
*/
protected void setFileInputValue( WebDriver webDriver, String value ) {

    String locator = this.getElementProperties()
                         .getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR);

    String css = this.getElementProperty("_css");

    WebElement element = null;

    if (!StringUtils.isNullOrEmpty(css)) {
        element = webDriver.findElement(By.cssSelector(css));
    } else {
        element = webDriver.findElement(By.xpath(locator));
    }

    try {
        element.sendKeys(value);
    } catch (ElementNotVisibleException enve) {

        if (!UiEngineConfigurator.getInstance().isWorkWithInvisibleElements()) {
            throw enve;
        }
        // try to make the element visible overriding some CSS properties
        // but keep in mind that it can be still invisible using another CSS and/or JavaScript techniques
        String styleAttrValue = element.getAttribute("style");
        JavascriptExecutor jsExec = (JavascriptExecutor) webDriver;
        try {
            jsExec.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                                 element,
                                 "display:'block'; visibility:'visible'; top:'auto'; left:'auto'; z-index:999;"
                                          + "height:'auto'; width:'auto';");
            element.sendKeys(value);
        } finally {
            jsExec.executeScript("arguments[0].setAttribute('style', arguments[1]);", element,
                                 styleAttrValue);
        }

    } catch (InvalidElementStateException e) {
        throw new SeleniumOperationException(e.getMessage(), e);
    }
}
 
Example 20
Source File: JavaScriptExecutor.java    From webtester-core with Apache License 2.0 3 votes vote down vote up
/**
 * Executes the given JavaScript code with the given parameters (accessible as arguments[0] - arguments[n]).
 * <p>
 * The JavaScripts return value is returned as described in {@link JavascriptExecutor#executeScript(String, Object...)}.
 *
 * @param script the JavaScript code to be executed on the current page
 * @param parameters any of Boolean, Long, String, List, WebElement or null.
 * @return the return value of the JavaScript
 * @see JavascriptExecutor#executeScript(String, Object...)
 * @since 1.2
 */
@SuppressWarnings("unchecked")
public <T> T executeWithReturn(String script, Object... parameters) {
    if (!(webDriver() instanceof JavascriptExecutor)) {
        throw new UnsupportedOperationException("WebDriver does not support JavaScript execution!");
    }
    JavascriptExecutor javascriptExecutor = ( JavascriptExecutor ) webDriver();
    return (T) javascriptExecutor.executeScript(script, parameters);
}