下面列出了怎么用org.openqa.selenium.JavascriptExecutor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Drags and drops element to specified place. Elements Need To have an id.
*
* @param from
* - the element to drag.
* @param to
* - the element to drop to.
*/
public void dragAndDropHtml5(final ExtendedWebElement from, final ExtendedWebElement to) {
String source = "#" + from.getAttribute("id");
String target = "#" + to.getAttribute("id");
if (source.isEmpty() || target.isEmpty()) {
Messager.ELEMENTS_NOT_DRAGGED_AND_DROPPED.error(from.getNameWithLocator(), to.getNameWithLocator());
} else {
jQuerify(driver);
String javaScript = "(function( $ ) { $.fn.simulateDragDrop = function(options) { return this.each(function() { new $.simulateDragDrop(this, options); }); }; $.simulateDragDrop = function(elem, options) { this.options = options; this.simulateEvent(elem, options); }; $.extend($.simulateDragDrop.prototype, { simulateEvent: function(elem, options) { /*Simulating drag start*/ var type = 'dragstart'; var event = this.createEvent(type); this.dispatchEvent(elem, type, event); /*Simulating drop*/ type = 'drop'; var dropEvent = this.createEvent(type, {}); dropEvent.dataTransfer = event.dataTransfer; this.dispatchEvent($(options.dropTarget)[0], type, dropEvent); /*Simulating drag end*/ type = 'dragend'; var dragEndEvent = this.createEvent(type, {}); dragEndEvent.dataTransfer = event.dataTransfer; this.dispatchEvent(elem, type, dragEndEvent); }, createEvent: function(type) { var event = document.createEvent(\"CustomEvent\"); event.initCustomEvent(type, true, true, null); event.dataTransfer = { data: { }, setData: function(type, val){ this.data[type] = val; }, getData: function(type){ return this.data[type]; } }; return event; }, dispatchEvent: function(elem, type, event) { if(elem.dispatchEvent) { elem.dispatchEvent(event); }else if( elem.fireEvent ) { elem.fireEvent(\"on\"+type, event); } } });})(jQuery);";;
((JavascriptExecutor)driver)
.executeScript(javaScript + "$('" + source + "')" +
".simulateDragDrop({ dropTarget: '" + target + "'});");
Messager.ELEMENTS_DRAGGED_AND_DROPPED.info(from.getName(), to.getName());
}
}
@Test
public void WebDriverProxy() throws InterruptedException, InstantiationException, IllegalAccessException, IOException {
checkPlatform();
proxy = klass.newInstance();
service = proxy.createService(findPort());
service.start();
driver = new RemoteWebDriver(service.getUrl(), capabilities);
driver.get("http://localhost:" + serverPort);
WebElement user = driver.findElement(By.cssSelector("#user_login"));
WebElement pass = driver.findElement(By.cssSelector("#user_pass"));
user.sendKeys("joe_bumkin");
pass.sendKeys("secret_words");
String value = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].value;", user);
AssertJUnit.assertEquals("joe_bumkin", value);
value = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].value;", pass);
AssertJUnit.assertEquals("secret_words", value);
driver.findElement(By.cssSelector("input"));
String url = (String) ((JavascriptExecutor) driver).executeScript("return document.URL;");
System.out.println("WebDriverProxyTest.WebDriverProxy(" + url + ")");
}
@Override
public List<WebElement> findElements(SearchContext searchContext) {
List<WebElement> result;
JavascriptExecutor executor = JavascriptHelper.getJavascriptExecutor(searchContext);
Object results = JavascriptHelper.executeScript(executor, script, scriptParameters);
if (results instanceof List) {
result = (List<WebElement>) results;
} else {
if (results == null) {
result = Collections.emptyList();
} else {
throw new RuntimeException("Script returned something else than a list: " + results);
}
}
return result;
}
private Wait getReadyStateUsingWait(final WebDriver driver) {
return new Wait() {
@Override
public boolean until() {
try {
Object result = ((JavascriptExecutor) driver).executeScript(
"return 'complete' == document.readyState;");
if (result instanceof Boolean && (Boolean) result) {
return true;
}
} catch (Exception e) {
// Possible page reload. Fine
}
return false;
}
};
}
@Test
public void testShouldUnpackMapOfElementArgsWhenCallingScripts() {
final WebDriver mockedDriver = mock(WebDriver.class,
withSettings().extraInterfaces(JavascriptExecutor.class));
final WebElement mockElement = mock(WebElement.class);
when(mockedDriver.findElement(By.id("foo"))).thenReturn(mockElement);
EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver);
testedDriver.register(mock(WebDriverEventListener.class));
final WebElement foundElement = testedDriver.findElement(By.id("foo"));
assertThat(foundElement).isInstanceOf(WrapsElement.class);
assertThat(((WrapsElement) foundElement).getWrappedElement()).isSameAs(mockElement);
ImmutableMap<String, Object> args = ImmutableMap.of(
"foo", "bar",
"element", foundElement,
"nested", Arrays.asList("before", foundElement, "after")
);
testedDriver.executeScript("foo", args);
verify((JavascriptExecutor) mockedDriver).executeScript("foo", args);
}
@Override
public void interactHiddenElementMouseEvent(
@NotNull final WebElement element,
@NotNull final String event,
@NotNull final JavascriptExecutor js) {
/*
PhantomJS doesn't support the click method, so "element.click()" won't work
here. We need to dispatch the event instead.
*/
js.executeScript("var ev = document.createEvent('MouseEvent');"
+ " ev.initMouseEvent("
+ " '" + event + "',"
+ " true /* bubble */, true /* cancelable */,"
+ " window, null,"
+ " 0, 0, 0, 0, /* coordinates */"
+ " false, false, false, false, /* modifier keys */"
+ " 0 /*left*/, null"
+ " );"
+ " arguments[0].dispatchEvent(ev);", element);
}
/**
* 时间控件不可编辑处理
* @param inputName
* @param time
* @param timeFormat
*/
public void timeWidgetMange(String inputName,String time,String timeFormat)
{
String date=formatDate(time, timeFormat);
String js="$(function(){$(\"input[name='"
+ inputName
+"']\""
+ ").removeAttr('readonly');"
+ "$(\"input[name='"
+ inputName
+"']\""
+ ").val(\""
+ date
+ "\");"
+ "})";
((JavascriptExecutor) driver).executeScript(js);
System.out.println(js);
}
/**
* Runs arbitrary JavaScript
*
* @param javaScript The JavaScript to run
* @param ignoreErrors Set this text to ignore an JavaScript errors
*/
@When("^I run the following JavaScript( ignoring errors)?$")
public void runJavaScript(final String ignoreErrors, final String javaScript) {
try {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final JavascriptExecutor js = (JavascriptExecutor) webDriver;
final List<String> aliases = State.getFeatureStateForThread().getDataSet().entrySet().stream()
.flatMap(it -> Stream.of(it.getKey(), it.getValue()))
.collect(Collectors.toList());
js.executeScript(javaScript, aliases);
} catch (final Exception ex) {
if (StringUtils.isBlank(ignoreErrors)) {
throw ex;
}
}
}
@Test
@NotYetImplemented(SAFARI)
public void testHoverPersists() throws Exception {
driver.get(pages.javascriptPage);
// Move to a different element to make sure the mouse is not over the
// element with id 'item1' (from a previous test).
new Actions(driver).moveToElement(driver.findElement(By.id("dynamo"))).build().perform();
WebElement element = driver.findElement(By.id("menu1"));
final WebElement item = driver.findElement(By.id("item1"));
assertThat(item.getText()).isEqualTo("");
((JavascriptExecutor) driver).executeScript("arguments[0].style.background = 'green'", element);
new Actions(driver).moveToElement(element).build().perform();
// Intentionally wait to make sure hover persists.
Thread.sleep(2000);
wait.until(not(elementTextToEqual(item, "")));
assertThat(item.getText()).isEqualTo("Item 1");
}
/**
* Updates a html file input with the path of the file to upload.
*
* @param pageElement
* Is target element.
* @param fileOrKey
* Is the file path (text or text in context (after a save)).
* @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_UPLOADING_FILE} message (with screenshot, no exception)
* @throws FailureException
* if the scenario encounters a functional error.
*/
protected void uploadFile(PageElement pageElement, String fileOrKey, Object... args) throws TechnicalException, FailureException {
final String path = Context.getValue(fileOrKey) != null ? Context.getValue(fileOrKey) : System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER + File.separator + fileOrKey;
if (!"".equals(path)) {
try {
final WebElement element = Wait.until(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(pageElement, args)));
element.clear();
if (DriverFactory.IE.equals(Context.getBrowser())) {
final String javascript = "arguments[0].value='" + path + "';";
((JavascriptExecutor) getDriver()).executeScript(javascript, element);
} else {
element.sendKeys(path);
}
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UPLOADING_FILE), path), true, pageElement.getPage().getCallBack());
}
} else {
log.debug("Empty data provided. No need to update file upload path. If you want clear data, you need use: \"I clear text in ...\"");
}
}
public InputStream download(String url) throws IOException {
String script = "var url = arguments[0];"
+ "var callback = arguments[arguments.length - 1];"
+ "var xhr = new XMLHttpRequest();"
+ "xhr.open('GET', url, true);"
+ "xhr.responseType = \"arraybuffer\";" +
// force the HTTP response, response-type header to be array
// buffer
"xhr.onload = function() {"
+ " var arrayBuffer = xhr.response;"
+ " var byteArray = new Uint8Array(arrayBuffer);"
+ " callback(byteArray);" + "};" + "xhr.send();";
Object response = ((JavascriptExecutor) getDriver())
.executeAsyncScript(script, url);
// Selenium returns an Array of Long, we need byte[]
ArrayList<?> byteList = (ArrayList<?>) response;
byte[] bytes = new byte[byteList.size()];
for (int i = 0; i < byteList.size(); i++) {
Long byt = (Long) byteList.get(i);
bytes[i] = byt.byteValue();
}
return new ByteArrayInputStream(bytes);
}
/**
* This method gets all facesmessages on the page.
* @param javascriptExecutor A {@link org.openqa.selenium.JavascriptExecutor JavascriptExecutor} as we need to execute some JavaScript
* @return A {@link com.redheap.selenium.domain.PageMessageWrapper PageMessageWrapper} with all facesmessages on
* the page as wel as some convenience methods.
*/
public static PageMessageWrapper getAllMessages(JavascriptExecutor javascriptExecutor) {
ArrayList<ArrayList> scriptResult =
(ArrayList<ArrayList>) javascriptExecutor.executeScript(FacesMessageDomain.JS_GET_PAGE_MESSAGES, "");
PageMessageWrapper pageMessageWrapper = new PageMessageWrapper();
if (scriptResult != null) {
//loop over all components
for (ArrayList compMessageList : scriptResult) {
String componentId = (String) compMessageList.get(0);
List<ArrayList> componentFacesMessages = (ArrayList<ArrayList>) compMessageList.get(1);
List<FacesMessageDomain> facesMessageDomainList = new ArrayList<FacesMessageDomain>();
for (ArrayList compMessage : componentFacesMessages) {
facesMessageDomainList.add(new FacesMessageDomain(componentId, compMessage));
}
pageMessageWrapper.addAllComponentMessages(componentId, facesMessageDomainList);
}
}
return pageMessageWrapper;
}
@Override
public void eval(String javaScript) {
try {
// TODO: add configuration for JavaScript executor
((JavascriptExecutor) wd).executeScript(javaScript);
// TODO: catch specific exceptions. If wd is not a JavaScript
// executor, don't bother waiting.
} catch (Exception e) {
long time = System.currentTimeMillis() + 2000;
boolean success = false;
while (!success && System.currentTimeMillis() < time) {
try {
((JavascriptExecutor) wd).executeScript(javaScript);
success = true;
} catch (Exception e2) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO: log
}
e = e2;
}
}
if (!success) {
// TODO: use specific exception type(s) for eval issues
throw new RuntimeException(e);
}
}
}
@Override
public BufferedImage getScreenshot(WebDriver wd, Set<Coords> coordsSet) {
JavascriptExecutor js = (JavascriptExecutor) wd;
int pageHeight = getFullHeight(wd);
int pageWidth = getFullWidth(wd);
int viewportHeight = getWindowHeight(wd);
shootingArea = getShootingCoords(coordsSet, pageWidth, pageHeight, viewportHeight);
int startY = getCurrentScrollY(js);
BufferedImage finalImage = new BufferedImage(pageWidth, shootingArea.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D graphics = finalImage.createGraphics();
int scrollTimes = (int) Math.ceil(shootingArea.getHeight() / viewportHeight);
for (int n = 0; n < scrollTimes; n++) {
scrollVertically(js, shootingArea.y + viewportHeight * n);
Sleeper.sleep(Duration.ofMillis(scrollTimeout));
BufferedImage part = getShootingStrategy().getScreenshot(wd);
int currentScrollY = getCurrentScrollY(js);
debugScreenshot(CURRENT_SCROLL + currentScrollY + "_part_" + n, part);
graphics.drawImage(part, 0, currentScrollY - shootingArea.y, null);
debugScreenshot(CURRENT_SCROLL + currentScrollY, finalImage);
}
graphics.dispose();
scrollVertically(js, startY);
return finalImage;
}
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);
});
}
@Override
public BufferedImage getScreenshot(WebDriver wd)
{
JavascriptExecutor executor = (JavascriptExecutor) wd;
int y = Math.toIntExact((Long) executor.executeScript("return window.pageYOffset;"));
int h = Math.toIntExact((Long) executor.executeScript("return window.innerHeight;"));
BufferedImage image = shootingStrategy.getScreenshot(wd);
return image.getSubimage(0, y, image.getWidth(), h);
}
@Override
public BufferedImage getScreenshot(WebDriver wd, Set<Coords> coordsSet)
{
JavascriptExecutor js = (JavascriptExecutor) wd;
int pageHeight = getFullHeight(wd);
int pageWidth = getFullWidth(wd);
int viewportHeight = getWindowHeight(wd);
Coords shootingArea = getShootingCoords(coordsSet, pageWidth, pageHeight, viewportHeight);
double heightRation = (double) correctedHeight / viewportHeight;
double widthRation = (double) correctedWidth / pageWidth;
BufferedImage finalImage = new BufferedImage(Math.toIntExact(Math.round(pageWidth * widthRation)),
Math.toIntExact(Math.round(shootingArea.height * heightRation * ACCURACY)), BufferedImage
.TYPE_3BYTE_BGR);
Graphics2D graphics = finalImage.createGraphics();
int scrollTimes = (int) Math.ceil(shootingArea.getHeight() / viewportHeight);
for (int n = 0; n < scrollTimes; n++)
{
scrollVertically(js, shootingArea.y + viewportHeight * n);
Sleeper.sleep(Duration.ofMillis(scrollTimeout));
BufferedImage part = getShootingStrategy().getScreenshot(wd);
graphics.drawImage(part, 0, Math.toIntExact(Math.round((getCurrentScrollY(js) - shootingArea.y)
* heightRation)), null);
}
graphics.dispose();
return finalImage;
}
@Override
protected int getCurrentScrollY(JavascriptExecutor js)
{
int currentScrollY = getScrollY(js);
if (scrolls != 0)
{
scrolls--;
return currentScrollY;
}
return currentScrollY + headerAdjustment;
}
/**
* Scrolls to the bottom of the page
*/
@When("^I scroll to the bottom of the page$")
public void scrollToBottom() {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final JavascriptExecutor js = JavascriptExecutor.class.cast(webDriver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
@Test
public void testDirection_initialPageDirection_setCorrectly() {
open("rtl");
// due to #8028 / 8029 need to wait for JS execution to complete
waitUntil(webDriver -> ((JavascriptExecutor) driver)
.executeScript(RETURN_DIR_SCRIPT), 2);
verifyDirection(Direction.RIGHT_TO_LEFT);
clickElementWithJs("ltr-button");
verifyDirection(Direction.LEFT_TO_RIGHT);
}
/**
* 显式等待 判断页面是否完全加载完成
* @param time 已秒为单位
*/
public void pagefoload(long time)
{
ExpectedCondition<Boolean> pageLoad= new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, time*1000);
wait.until(pageLoad);
}
/**
* An expectation for String value from javascript
*
* @param javaScript as executable js line
* @return true once js return string
*/
public static ExpectedCondition<Object> jsReturnsValue(final String javaScript) {
return new ExpectedCondition<Object>() {
@Override
public Object apply(WebDriver driver) {
try {
Object value = ((JavascriptExecutor) driver).executeScript(javaScript);
if (value instanceof List) {
return ((List<?>) value).isEmpty() ? null : value;
}
if (value instanceof String) {
return ((String) value).isEmpty() ? null : value;
}
return value;
} catch (WebDriverException e) {
return null;
}
}
@Override
public String toString() {
return String.format("js %s to be executable", javaScript);
}
};
}
@Override
protected String handleSeleneseCommand(WebDriver driver, String locator, String value) {
JavascriptExecutor js = (JavascriptExecutor) driver;
String s = String.format("return var script = document.createElement(\"script\");"
+ "script.setAttribute('type','text/javascript'); " + "script.setAttribute('src','%s');"
+ "document.body.appendChild(script); ", locator);
js.executeScript(s);
return "";
}
private boolean enterWithJS(WebDriver driver) {
try {
String enterCmd = "var keyboardEvent = document.createEvent('KeyboardEvent');" +
"var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';" +
"keyboardEvent[initMethod]('keydown',true,true,window,false,false,false,false,13,0);document.dispatchEvent(keyboardEvent);";
((JavascriptExecutor) driver).executeScript(enterCmd);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Waits until the given element is clickable and perform the click event.
*
* @param driver selenium web driver.
* @param locator locator of the element.
* @throws InterruptedException If error occurs with thread execution.
*/
public static void waitAndClick(WebDriver driver, By locator) throws InterruptedException {
Actions actions = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(locator));
WebElement webElement = driver.findElement(locator);
/*
There is a issue in Selenium Chrome Driver where it performs click event in wrong places (#633). Mostly occur
when the element to be clicked is placed outside the visible area. To overcome this issue scrolling the page to
the element locator through a JavascriptExecutor
*/
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", webElement);
Thread.sleep(500);
actions.moveToElement(webElement).click().build().perform();
}
protected void sendEvent(WebElement el, String type) {
StringBuilder script = new StringBuilder(
"return (function(a,b,c,d){" +
"c=document," +
"c.createEvent" +
"?(d=c.createEvent('HTMLEvents'),d.initEvent(b,!0,!0),a.dispatchEvent(d))" +
":(d=c.createEventObject(),a.fireEvent('on'+b,d))})"
);
script.append("(arguments[0],'").append(type.replace("'", "\\'")).append("');");
((JavascriptExecutor)getDriver()).executeScript(script.toString(), el);
}
@Test
void shouldPerformActionWithHiddenScrollbarForScrollableElement()
{
when(webDriverProvider.get()).thenReturn(webDriver);
Object object = mock(Object.class);
WebElement scrollableElement = mock(WebElement.class);
String hideScript = "var originalStyleOverflow = arguments[0].style.overflow;"
+ "arguments[0].style.overflow='hidden';return originalStyleOverflow;";
when(((JavascriptExecutor) webDriver).executeScript(hideScript, scrollableElement)).thenReturn(object);
scrollbarHandler.performActionWithHiddenScrollbars(action, scrollableElement);
verify((JavascriptExecutor) webDriver).executeScript(eq(hideScript), nullable(WebElement.class));
verify((JavascriptExecutor) webDriver).executeScript("arguments[0].style.overflow=arguments[1];",
scrollableElement, object);
}
@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);
}
}
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;");
}
}
@Test
void testAfterNavigateToAcceptAlert()
{
pageLoadListenerForAlertHanding.setAlertHandlingOptions(AlertHandlingOptions.ACCEPT);
pageLoadListenerForAlertHanding.afterNavigateTo(URL, webDriver);
verify((JavascriptExecutor) webDriver).executeScript(ALERT_SCRIPT, true);
}