Java Code Examples for org.openqa.selenium.JavascriptExecutor


Document 对象方法

方法 描述
close() 关闭用 document.open() 方法打开的输出流,并显示选定的数据。
getElementById() 返回对拥有指定 id 的第一个对象的引用。
getElementsByName() 返回带有指定名称的对象集合。
getElementsByTagName() 返回带有指定标签名的对象集合。
open() 打开一个流,以收集来自任何 document.write() 或 document.writeln() 方法的输出。
write() 向文档写 HTML 表达式 或 JavaScript 代码。
writeln() 等同于 write() 方法,不同的是在每个表达式之后写一个换行符。

Document 对象描述

HTMLDocument 接口对 DOM Document 接口进行了扩展,定义 HTML 专用的属性和方法。

很多属性和方法都是 HTMLCollection 对象(实际上是可以用数组或名称索引的只读数组),其中保存了对锚、表单、链接以及其他可脚本元素的引用。

这些集合属性都源自于 0 级 DOM。它们已经被 Document.getElementsByTagName() 所取代,但是仍然常常使用,因为他们很方便。

write() 方法值得注意,在文档载入和解析的时候,它允许一个脚本向文档中插入动态生成的内容。

注意,在 1 级 DOM 中,HTMLDocument 定义了一个名为 getElementById() 的非常有用的方法。在 2 级 DOM 中,该方法已经被转移到了 Document 接口,它现在由 HTMLDocument 继承而不是由它定义了。



The following code examples are extracted from open source projects. You can click Java Code Examples for org.openqa.selenium.JavascriptExecutor_第1张图片 to vote up the examples you like. The votes will be used to predict good API usage examples and more good examples will be extracted based on the votes.

Code Example 1:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第2张图片

From project mfp-qa, under directory /mfp-qa/src/main/java/com/myfitnesspal/qa/pages/user/.

Source AddFoodPage.java

public FoodDiaryPage addCheckedFoodLine(int foodNumber, int foodQuantity, int foodWeightOptionNumber)
{

	String checkboxId = String.format(CHECKBOX_TO_MARK_FOOD_ID, foodNumber);
	String fieldQuantityId = String.format(QUANTITY_OF_ADDED_FOOD_ID, foodNumber);
	String selectFoodWeightId = String.format(WEIGHT_OF_ADDED_FOOD_ID, foodNumber);
	int optionsCount = driver.findElement(By.id(selectFoodWeightId)).findElements(By.xpath(".//option")).size();

	JavascriptExecutor js = (JavascriptExecutor) driver;
	js.executeScript(String.format("document.getElementById('%s').click()", checkboxId));
	Messager.ELEMENT_CLICKED.info("check box of food to add");
	js.executeScript(String.format("document.getElementById('%s').value='%d'", fieldQuantityId, foodQuantity));
	Messager.KEYS_SEND_TO_ELEMENT.info(String.valueOf(foodQuantity), "serving count");
	js.executeScript(String.format("document.getElementById('%s').selectedIndex='%d'", selectFoodWeightId,
			optionsCount >= foodWeightOptionNumber + 1 ? foodWeightOptionNumber : 0));
	Messager.ELEMENT_CLICKED.info("selectFoodWeightId item");
	click("btn Add Checked", btnAddChecked);
	return PageFactory.initElements(driver, FoodDiaryPage.class);
}
 

Code Example 2:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第3张图片

From project mfp-qa, under directory /mfp-qa-v2.0/src/main/java/com/myfitnesspal/qa/foundation/.

Source DriverHelper.java

public void setElementText(String controlInfo, String frame, String id, String text) {
	((JavascriptExecutor) driver).executeScript(String.format(
			"document.getElementById('%s').contentWindow.document.getElementById('%s').innerHTML='%s'", frame, id,
			text));
	String msg = Messager.KEYS_SEND_TO_ELEMENT.info(text, controlInfo);
	summary.write(msg);
	TestSummaryCollector.pushScreenStep(Screenshot.take(driver), msg);
	SessionStatusCollector.sendAlive(driver);
}
 

Code Example 3:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第4张图片

From project mfp-qa, under directory /mfp-qa-v2.0/src/main/java/com/myfitnesspal/qa/foundation/.

Source DriverHelper.java

public void sielentAlert() {
	if (!(driver instanceof HtmlUnitDriver)) {
		((JavascriptExecutor) driver).executeScript("window.alert = function(msg) { return true; }");
		((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
		((JavascriptExecutor) driver).executeScript("window.prompt = function(msg) { return true; }");
	}
}
 

Code Example 4:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第5张图片

From project mfp-qa, under directory /mfp-qa-v2.0/src/main/java/com/myfitnesspal/qa/pages/user/.

Source AddFoodPage.java

public FoodDiaryPage addCheckedFoodLine(int foodNumber, int foodQuantity, int foodWeightOptionNumber)
{

	String checkboxId = String.format(CHECKBOX_TO_MARK_FOOD_ID, foodNumber);
	String fieldQuantityId = String.format(QUANTITY_OF_ADDED_FOOD_ID, foodNumber);
	String selectFoodWeightId = String.format(WEIGHT_OF_ADDED_FOOD_ID, foodNumber);
	int optionsCount = driver.findElement(By.id(selectFoodWeightId)).findElements(By.xpath(".//option")).size();

	JavascriptExecutor js = (JavascriptExecutor) driver;
	js.executeScript(String.format("document.getElementById('%s').click()", checkboxId));
	Messager.ELEMENT_CLICKED.info("check box of food to add");
	js.executeScript(String.format("document.getElementById('%s').value='%d'", fieldQuantityId, foodQuantity));
	Messager.KEYS_SEND_TO_ELEMENT.info(String.valueOf(foodQuantity), "serving count");
	js.executeScript(String.format("document.getElementById('%s').selectedIndex='%d'", selectFoodWeightId,
			optionsCount >= foodWeightOptionNumber + 1 ? foodWeightOptionNumber : 0));
	Messager.ELEMENT_CLICKED.info("selectFoodWeightId item");
	click("btn Add Checked", btnAddChecked);
	return PageFactory.initElements(driver, FoodDiaryPage.class);
}
 

Code Example 5:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第6张图片

From project thucydides, under directory /thucydides-core/src/test/java/net/thucydides/core/pages/integration/.

Source WhenResizingTheBrower.java

@Test
public void should_resize_chrome_automatically() {
    environmentVariables.setProperty("thucydides.browser.height", "200");
    environmentVariables.setProperty("thucydides.browser.width", "400");

    driver = factory.newInstanceOf(SupportedWebDriver.CHROME);
    page = new StaticSitePage(driver, 1000);
    page.open();

    int width = ((Long)(((JavascriptExecutor)driver).executeScript("return window.innerWidth"))).intValue();
    assertThat(width, allOf(lessThanOrEqualTo(400), greaterThan(380)));
}
 

Code Example 6:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第7张图片

From project thucydides, under directory /thucydides-core/src/test/java/net/thucydides/core/pages/integration/.

Source WhenResizingTheBrower.java

@Test
public void should_resize_firefox_automatically() {
    environmentVariables.setProperty("thucydides.browser.height", "200");
    environmentVariables.setProperty("thucydides.browser.width", "400");

    driver = factory.newInstanceOf(SupportedWebDriver.FIREFOX);
    page = new StaticSitePage(driver, 1000);
    page.open();

    int width = ((Long)(((JavascriptExecutor)driver).executeScript("return window.innerWidth"))).intValue();
    assertThat(width, allOf(lessThanOrEqualTo(400), greaterThan(380)));
}
 

Code Example 7:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第8张图片

From project thucydides, under directory /thucydides-core/src/main/java/net/thucydides/core/webdriver/javascript/.

Source JavascriptExecutorFacade.java

public Object executeScript(final String script) {
    if (javascriptIsSupportedIn(driver)) {
        JavascriptExecutor js = getJavascriptEnabledDriver();
        return js.executeScript(script);
    } else {
        return null;
    }
}
 

Code Example 8:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第9张图片

From project thucydides, under directory /thucydides-core/src/main/java/net/thucydides/core/webdriver/javascript/.

Source JavascriptExecutorFacade.java

public Object executeScript(final String script, final Object... params) {
    if (javascriptIsSupportedIn(driver)) {
        JavascriptExecutor js = getJavascriptEnabledDriver();
        return js.executeScript(script, params);
    } else {
        return null;
    }
}
 

Code Example 9:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第10张图片

From project thucydides, under directory /thucydides-core/src/main/java/net/thucydides/core/webdriver/jquery/.

Source ByJQuerySelector.java

@Override
public WebElement findElement(SearchContext context) {
    String jquery = "return $(" + quoted(jQuerySelector) + ").get(0);";
    WebElement element = (WebElement) ((JavascriptExecutor) context).executeScript(jquery);
    if (element == null) {
        throw new NoSuchElementException("No element found matching JQuery selector " + jQuerySelector);
    } else {
        return element;
    }

}
 

Code Example 10:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第11张图片

From project thucydides, under directory /thucydides-core/src/main/java/net/thucydides/core/webdriver/.

Source WebDriverFactory.java

protected void resizeBrowserTo(WebDriver driver, int height, int width) {

    LOGGER.info("Setting browser dimensions to {}/{}", height, width);

    if (usesFirefox(driver) || usesInternetExplorer(driver)) {
        driver.manage().window().setSize(new Dimension(width, height));
    } else if (usesChrome(driver)) {
        ((JavascriptExecutor) driver).executeScript("window.open('about:blank','_blank','width=#{width},height=#{height}');");
        Set<String> windowHandles = driver.getWindowHandles();
        windowHandles.remove(driver.getWindowHandle());
        String newWindowHandle = windowHandles.toArray(new String[]{})[0];
        driver.switchTo().window(newWindowHandle);
    }
    String resizeWindow = "window.resizeTo(" + width + "," + height + ")";
    ((JavascriptExecutor) driver).executeScript(resizeWindow);
}
 

Code Example 11:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第12张图片

From project Cafe, under directory /webapp/src/org/openqa/selenium/android/.

Source AndroidWebDriver.java

private String executeJavascriptInWebView(final String script) {
  if (webview == null) {
    throw new WebDriverException("No open windows.");
  }
  result = null;
  resultReady = false;
  activity.runOnUiThread(new Runnable() {
    public void run() {
      org.openqa.selenium.android.JavascriptExecutor.executeJs(
          webview, notifier, script);
    }
  });
  long timeout = System.currentTimeMillis() + RESPONSE_TIMEOUT;
  synchronized (syncObject) {
    while (!resultReady && (System.currentTimeMillis() < timeout)) {
      try {
        syncObject.wait(RESPONSE_TIMEOUT);
      } catch (InterruptedException e) {
        throw new WebDriverException(e);
      }
    }
    return result;
  }
}
 

Code Example 12:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第13张图片

From project jasmine-maven-plugin, under directory /src/main/java/com/github/searls/jasmine/runner/.

Source SpecRunnerExecutor.java

public JasmineResult execute(URL runnerUrl, File junitXmlReport, WebDriver driver, int timeout, boolean debug, Log log, String format) {
  try {
    if (!(driver instanceof JavascriptExecutor)) {
      throw new RuntimeException("The provided web driver can't execute JavaScript: " + driver.getClass());
    }
    JavascriptExecutor executor = (JavascriptExecutor) driver;
      driver.get(runnerUrl.toString());
      waitForRunnerToFinish(driver, timeout, debug, log);
      JasmineResult jasmineResult = new JasmineResult();
      jasmineResult.setDetails(buildReport(executor,format));
      fileUtilsWrapper.writeStringToFile(junitXmlReport, buildJunitXmlReport(executor,debug), "UTF-8");
      driver.quit();

      return jasmineResult;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 

Code Example 13:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第14张图片

From project jasmine-maven-plugin, under directory /src/main/java/com/github/searls/jasmine/runner/.

Source SpecRunnerExecutor.java

private String buildReport(JavascriptExecutor driver, String format) throws IOException {
  String script =
      ioUtilsWrapper.toString(BUILD_REPORT_JS) +
      "return jasmineMavenPlugin.printReport(window.reporter,{format:'"+format+"'});";
  Object report = driver.executeScript(script);
  return report.toString();
}
 

Code Example 14:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第15张图片

From project jasmine-maven-plugin, under directory /src/main/java/com/github/searls/jasmine/runner/.

Source SpecRunnerExecutor.java

private String buildJunitXmlReport(JavascriptExecutor driver, boolean debug) throws IOException {
  Object junitReport = driver.executeScript(
      ioUtilsWrapper.toString(CREATE_JUNIT_XML) +
      "return junitXmlReporter.report(window.reporter,"+debug+");");
  return junitReport.toString();
}
 

Code Example 15:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第16张图片

From project jasmine-maven-plugin, under directory /src/main/java/com/github/searls/jasmine/runner/.

Source SpecRunnerExecutor.java

private void waitForRunnerToFinish(final WebDriver driver, int timeout, boolean debug, Log log) throws InterruptedException {
  final JavascriptExecutor executor = (JavascriptExecutor) driver;
  new WebDriverWait(driver, timeout, 1000).until(new Predicate<WebDriver>() {
    public boolean apply(WebDriver input) {
      return executionFinished(executor);
    }
  });

  if (!executionFinished(executor)) {
    handleTimeout(timeout, debug, log);
  }
}
 

Code Example 16:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第17张图片

From project FluentLenium, under directory /fluentlenium-core/src/main/java/org/fluentlenium/core/wait/.

Source FluentWaitPageMatcher.java

public Fluent isLoaded() {

    if (!(webDriver instanceof JavascriptExecutor)) {
        throw new UnsupportedOperationException("Driver must support javascript execution to use this feature");
    } else {
        Predicate isLoaded = new com.google.common.base.Predicate<WebDriver>() {
            public boolean apply(@Nullable WebDriver webDriver) {
                JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
                Object result = javascriptExecutor.executeScript("if (document.readyState) return document.readyState;");
                if (result != null) {
                    return "complete".equals((String) result);

                }
                return false;
            }
        };
        FluentWaitMatcher.until(wait, isLoaded, filters, isPageLoaded(webDriver.getCurrentUrl()));
    }

    return FluentThread.get();

}
 

Code Example 17:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第18张图片

From project parallel-webtest, under directory /src/test/java/com/dynacrongroup/webtest/webdriverbase/.

Source WebDriverUtilitiesTest.java

@Test
public void reduceToOneWindowTest() throws Exception {
    getLogger().info("Starting test [{}]", name.getMethodName());
    String testUrl = "http://www.google.com/";


    assertThat(driver.getWindowHandles().size(), equalTo(1));
    ((JavascriptExecutor)driver).executeScript("window.open(\"" + testUrl + "\")");
    assertThat(driver.getWindowHandles().size(), equalTo(2));
    WebDriverUtilities.reduceToOneWindow(driver);
    assertThat(driver.getWindowHandles().size(), equalTo(1));

}
 

Code Example 18:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第19张图片

From project parallel-webtest, under directory /src/test/java/com/dynacrongroup/webtest/webdriverbase/.

Source WebDriverUtilitiesTest.java

@Test
public void switchToNewPopUpTest() {
    getLogger().info("Starting test [{}]", name.getMethodName());
    String testUrl = "http://www.google.com/";

    ((JavascriptExecutor)driver).executeScript("window.open(\"" + testUrl + "\")");
    assertThat(driver.getWindowHandles().size(), equalTo(2));
    WebDriverUtilities.switchToNewPopUp(driver);
    assertThat(driver.getCurrentUrl(), equalTo(testUrl));
}
 

Code Example 19:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第20张图片

From project parallel-webtest, under directory /src/main/java/com/dynacrongroup/webtest/rule/.

Source SauceLabsLogger.java

void sendContextMessage(String message) {
    try {
        ((JavascriptExecutor) wrapper.getDriver()).executeScript("sauce:context=// " + message);
    } catch (WebDriverException exception) {
        LOG.warn("Failed to update sauce labs context: {}", exception.getMessage());
    }
}
 

Code Example 20:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第21张图片

From project qa, under directory /archetypes/richfaces-kitchensink-ftest/src/test/java/org/richfaces/tests/archetypes/kitchensink/ftest/common/page/.

Source RegisterForm.java

public void switchOffAutocompleteOnInputs(WebDriver webDriver) {
    JavascriptExecutor js = (JavascriptExecutor) webDriver;
    js.executeScript("document.getElementsByName('mobileForm:memberForm:name')[0].setAttribute('autocomplete','off');");
    js.executeScript("document.getElementsByName('mobileForm:memberForm:email')[0].setAttribute('autocomplete','off');");
    js.executeScript("document.getElementsByName('mobileForm:memberForm:phoneNumber')[0].setAttribute('autocomplete','off');");
}
 

Code Example 21:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第22张图片

From project qa, under directory /showcase-webdriver-ftest/src/test/java/org/richfaces/tests/showcase/ftest/webdriver/page/.

Source AbstractTreePage.java

private void toggle(WebElement toToggle) {
    if (webDriver instanceof JavascriptExecutor) {
        Point location = toToggle.getLocation();
        JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver;
        jsExecutor.executeScript("window.moveTo(" + location.getX() + ", " + location.getY() + ")");
    }
    toToggle.click();
    Graphene.waitAjax()
        .withMessage("Unable to toggle the given element.")
        .until(Graphene.element(toToggle).isPresent());
}
 

Code Example 22:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第23张图片

From project qa, under directory /metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/.

Source AbstractWebDriverTest.java

protected String expectedReturnJS(String script, String expectedValue, Object... args) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String result = null;
    for (int i = 0; i < TRIES; i++) {
        Object executeScript = js.executeScript(script, args);
        if (executeScript != null) {
            result = ((String) js.executeScript(script, args)).trim();
            if (result.equals(expectedValue)) {
                break;
            }
        }
        waiting(MINOR_WAIT_TIME);
    }
    return result;
}
 

Code Example 23:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第24张图片

From project qa, under directory /metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/webdriver/.

Source Attributes.java

private void applyText(String propertyName, String value) {
    By cssSelector = By.cssSelector("[id$=':" + propertyName + "Input']");
    String text = driver.findElement(cssSelector).getAttribute("value");
    if (!value.equals(text)) {
        if (!text.isEmpty()) {
            ((JavascriptExecutor) driver).executeScript("$(\"input[id$=':" + propertyName + "Input']\").val('')");
        }
        waitUntilElementIsVisible(cssSelector).sendKeys(value);
        waitGuard(driver.findElement(cssSelector)).submit();
    }
}
 

Code Example 24:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第25张图片

From project qa, under directory /metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/a4jAjax/.

Source AbstractAjaxTest.java

public void testData() {
    ajaxAttributes.set(AjaxAttributes.data, "RichFaces 4 data");
    ajaxAttributes.set(AjaxAttributes.oncomplete, "data = event.data");

    String reqTime = page.requestTime.getText();
    performAction();
    Graphene.waitModel().withMessage("Page was not updated")
        .until(Graphene.element(page.requestTime).not().textEquals(reqTime));

    String data = ((JavascriptExecutor) driver).executeScript("return data").toString();
    assertEquals(data, "RichFaces 4 data", "Data sent with ajax request");
}
 

Code Example 25:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第26张图片

From project qa, under directory /metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/a4jAjax/.

Source AbstractAjaxTest.java

public void testEvents() {
    ajaxAttributes.set(AjaxAttributes.onbeforesubmit, "metamerEvents += \"beforesubmit \"");
    ajaxAttributes.set(AjaxAttributes.onbegin, "metamerEvents += \"begin \"");
    ajaxAttributes.set(AjaxAttributes.onbeforedomupdate, "metamerEvents += \"beforedomupdate \"");
    ajaxAttributes.set(AjaxAttributes.oncomplete, "metamerEvents += \"complete \"");

    ((JavascriptExecutor) driver).executeScript("metamerEvents = \"\"");
    String reqTime = page.requestTime.getText();
    performAction();
    Graphene.waitModel().withMessage("Page was not updated")
        .until(Graphene.element(page.requestTime).not().textEquals(reqTime));

    String[] events = ((JavascriptExecutor) driver).executeScript("return metamerEvents").toString().split(" ");

    assertEquals(events.length, 4, "4 events should be fired.");
    assertEquals(events[0], "beforesubmit", "Attribute onbeforesubmit doesn't work");
    assertEquals(events[1], "begin", "Attribute onbegin doesn't work");
    assertEquals(events[2], "beforedomupdate", "Attribute onbeforedomupdate doesn't work");
    assertEquals(events[3], "complete", "Attribute oncomplete doesn't work");
}
 

Code Example 26:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第27张图片

From project qa, under directory /metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/a4jAjax/.

Source AbstractAjaxTest.java

public void testEventsForTextInputs() {
    ajaxAttributes.set(AjaxAttributes.onbeforesubmit, "metamerEvents += \"beforesubmit \"");
    ajaxAttributes.set(AjaxAttributes.onbegin, "metamerEvents += \"begin \"");
    ajaxAttributes.set(AjaxAttributes.onbeforedomupdate, "metamerEvents += \"beforedomupdate \"");
    ajaxAttributes.set(AjaxAttributes.oncomplete, "metamerEvents += \"complete \"");

    ((JavascriptExecutor) driver).executeScript("metamerEvents = \"\"");
    final String text = "RichFaces";

    for (int i = 1; i <= text.length(); i++) {
        ((JavascriptExecutor) driver).executeScript("$(\"[id$=input]\").val('"
            + text.substring(0, i) + "');");
        ((JavascriptExecutor) driver).executeScript("$(\"[id$=input]\").trigger('keyup');");
        Graphene.waitModel().withMessage("Page was not updated")
            .until(Graphene.element(page.output1).textEquals(text.substring(0, i)));
    }

    String[] events = ((JavascriptExecutor) driver).executeScript("return metamerEvents").toString().split(" ");

    assertEquals(events.length, 36, "36 events should be fired.");
    assertEquals(events[0], "beforesubmit", "Attribute onbeforesubmit doesn't work");
    assertEquals(events[1], "begin", "Attribute onbegin doesn't work");
    assertEquals(events[2], "beforedomupdate", "Attribute onbeforedomupdate doesn't work");
    assertEquals(events[3], "complete", "Attribute oncomplete doesn't work");
}
 

Code Example 27:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第28张图片

From project qa, under directory /metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/a4jAjax/.

Source AbstractAjaxTest.java

protected void typeKeys(String text) {
    for (int i = 1; i <= text.length(); i++) {
        ((JavascriptExecutor) driver).executeScript("$(\"[id$=input]\").val('"
            + text.substring(0, i) + "');");
        ((JavascriptExecutor) driver).executeScript("$(\"[id$=input]\").trigger('keyup');");
    }
}
 

Code Example 28:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第29张图片

From project qa, under directory/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/a4jCommandButton/.

Source TestA4JCommandButton.java

@Test
public void testEvents() {
    commandLinkAttributes.set(CommandLinkAttributes.onbegin, "metamerEvents += \"begin \"");
    commandLinkAttributes.set(CommandLinkAttributes.onbeforedomupdate, "metamerEvents += \"beforedomupdate \"");
    commandLinkAttributes.set(CommandLinkAttributes.oncomplete, "metamerEvents += \"complete \"");

    ((JavascriptExecutor) driver).executeScript("metamerEvents = \"\"");
    String reqTime = page.requestTime.getText();
    Graphene.guardXhr(page.button).click();
    Graphene.waitModel().withMessage("Page was not updated")
        .until(Graphene.element(page.requestTime).not().textEquals(reqTime));

    String[] events = ((JavascriptExecutor) driver).executeScript("return metamerEvents").toString().split(" ");

    assertEquals(events.length, 3, "3 events should be fired.");
    assertEquals(events[0], "begin", "Attribute onbegin doesn't work");
    assertEquals(events[1], "beforedomupdate", "Attribute onbeforedomupdate doesn't work");
    assertEquals(events[2], "complete", "Attribute oncomplete doesn't work");
}
 

Code Example 29:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第30张图片

From project qa, under directory/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/a4jCommandLink/.

Source TestA4JCommandLink.java

@Test
public void testEvents() {
    commandLinkAttributes.set(CommandLinkAttributes.onbegin, "metamerEvents += \"begin \"");
    commandLinkAttributes.set(CommandLinkAttributes.onbeforedomupdate, "metamerEvents += \"beforedomupdate \"");
    commandLinkAttributes.set(CommandLinkAttributes.oncomplete, "metamerEvents += \"complete \"");

    ((JavascriptExecutor) driver).executeScript("metamerEvents = \"\"");
    String reqTime = page.requestTime.getText();
    page.submitByLink();
    Graphene.waitModel().withMessage("Page was not updated")
        .until(Graphene.element(page.requestTime).not().textEquals(reqTime));

    String[] events = ((JavascriptExecutor) driver).executeScript("return metamerEvents").toString().split(" ");

    assertEquals(events.length, 3, "3 events should be fired.");
    assertEquals(events[0], "begin", "Attribute onbegin doesn't work");
    assertEquals(events[1], "beforedomupdate", "Attribute onbeforedomupdate doesn't work");
    assertEquals(events[2], "complete", "Attribute oncomplete doesn't work");
}
 

Code Example 30:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第31张图片

From project qa, under directory/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richAccordion/.

Source TestRichAccordionWebDriver.java

@Test
public void testCycledSwitching() {
    String accordionId = ((JavascriptExecutor) driver).executeScript("return testedComponentId").toString();
    Object result = null;

    // RichFaces.$('form:accordion').nextItem('item4') will be null
    result = ((JavascriptExecutor) driver).executeScript("return RichFaces.$('" + accordionId
        + "').nextItem('item4')");
    assertEquals(result, null, "Result of function nextItem('item4')");

    // RichFaces.$('form:accordion').prevItem('item1') will be null
    result = ((JavascriptExecutor) driver).executeScript("return RichFaces.$('" + accordionId
        + "').prevItem('item1')");
    assertEquals(result, null, "Result of function prevItem('item1')");

    accordionAttributes.set(AccordionAttributes.cycledSwitching, true);

    // RichFaces.$('form:accordion').nextItem('item5') will be item1
    result = ((JavascriptExecutor) driver).executeScript("return RichFaces.$('" + accordionId
        + "').nextItem('item5')");
    assertEquals(result.toString(), "item1", "Result of function nextItem('item5')");

    // RichFaces.$('form:accordion').prevItem('item1') will be item5
    result = ((JavascriptExecutor) driver).executeScript("return RichFaces.$('" + accordionId
        + "').prevItem('item1')");
    assertEquals(result.toString(), "item5", "Result of function prevItem('item1')");
}
 

Code Example 31:

  1 
Java Code Examples for org.openqa.selenium.JavascriptExecutor_第32张图片

From project jbehave-web, under directory /web-selenium/src/main/java/org/jbehave/web/selenium/.

Source SauceContextStoryReporter.java

@Override
public void beforeScenario(String title) {
    try {
        super.beforeScenario(title);
        ((JavascriptExecutor) webDriverProvider.get()).executeScript("sauce:context=Scenario: " + title);
        // This should really be done per Story, but the webDriverProvider has not done it's thing for this thread yet :-(
        sessionIds.set(((RemoteWebDriver) webDriverProvider.get()).getSessionId());
        String payload = "{\"tags\":[" + getJobTags() + "], " + getBuildId() + "\"name\":\" " + getJobName() + "\"}";
        postJobUpdate(storyName.get(), sessionIds.get(), payload);
    } catch (WebDriverException e) {
        if (e.getMessage().startsWith("Error communicating with the remote browser. It may have died.")) {
            // do nothing, it's likely that SauceLabs timed out the job on their system.
        } else {
            throw e;
        }
    }
}

你可能感兴趣的:(Java Code Examples for org.openqa.selenium.JavascriptExecutor)