org.openqa.selenium.JavascriptExecutor Java Examples
The following examples show how to use
org.openqa.selenium.JavascriptExecutor.
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: BasicMouseInterfaceTest.java From selenium with Apache License 2.0 | 6 votes |
@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"); }
Example #2
Source File: TimeUtil.java From PatatiumAppUi with GNU General Public License v2.0 | 6 votes |
/** * 时间控件不可编辑处理 * @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); }
Example #3
Source File: StreamResourceIT.java From flow with Apache License 2.0 | 6 votes |
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); }
Example #4
Source File: JavaScriptRunnerImpl.java From IridiumApplicationTesting with MIT License | 6 votes |
@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); }
Example #5
Source File: JavascriptBy.java From hsac-fitnesse-fixtures with Apache License 2.0 | 6 votes |
@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; }
Example #6
Source File: WaitForPageToLoad.java From selenium with Apache License 2.0 | 6 votes |
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; } }; }
Example #7
Source File: WebDriverProxyTest.java From marathonv5 with Apache License 2.0 | 6 votes |
@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 + ")"); }
Example #8
Source File: JavaScriptStepDefinitions.java From IridiumApplicationTesting with MIT License | 6 votes |
/** * 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; } } }
Example #9
Source File: EventFiringWebDriverTest.java From selenium with Apache License 2.0 | 6 votes |
@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); }
Example #10
Source File: Step.java From NoraUi with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 ...\""); } }
Example #11
Source File: PageMessageWrapper.java From adf-selenium with Apache License 2.0 | 6 votes |
/** * 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; }
Example #12
Source File: DriverHelper.java From carina with Apache License 2.0 | 6 votes |
/** * 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()); } }
Example #13
Source File: JavascriptActionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void shouldScrollToTheStartOfWebElement() { WebElement webElement = mock(WebElement.class); javascriptActions.scrollToLeftOf(webElement); verify((JavascriptExecutor) webDriver).executeScript("arguments[0].scrollLeft=0;", webElement); }
Example #14
Source File: TestJavaApplicationOverviewUtil.java From windup with Eclipse Public License 1.0 | 5 votes |
/** * Returns the xpath full path of the given element. E.g something like /html/body/div[2]/p * * @param driver * @param element * @return */ private String getElementXPath(WebDriver driver, WebElement element) { String xpath = (String) ((JavascriptExecutor) driver).executeScript( "gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element); if (!StringUtils.startsWith(xpath, "id(\"")) xpath = "/html/" + xpath; return xpath; }
Example #15
Source File: CommonMethods.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 5 votes |
@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 #16
Source File: JavascriptActionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testSetElementTopPosition() { WebElement webElement = mock(WebElement.class); Long top = 10L; when(((JavascriptExecutor) webDriver).executeScript(String.format(SCRIPT_SET_TOP_POSITION, top), webElement)) .thenReturn(top); int resultTop = javascriptActions.setElementTopPosition(webElement, top.intValue()); assertEquals(top.intValue(), resultTop); }
Example #17
Source File: AdjustingCoordsProviderTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testGetCoordsIOS() { mockScrollbarActions(); when(webDriverManager.isIOS()).thenReturn(Boolean.TRUE); when(webElement.getLocation()).thenReturn(new Point(X, 0)); when(webElement.getSize()).thenReturn(new Dimension(WIDTH, HEIGHT)); when(((JavascriptExecutor) webDriver).executeScript(SCRIPT)).thenReturn((long) Y); Coords coords = adjustingCoordsProvider.ofElement(webDriver, webElement); verifyCoords(coords); }
Example #18
Source File: JavascriptActionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testScrollIntoView() { WebElement webElement = mock(WebElement.class); javascriptActions.scrollIntoView(webElement, true); verify((JavascriptExecutor) webDriver).executeScript("arguments[0].scrollIntoView(arguments[1])", webElement, true); }
Example #19
Source File: CleanSessionTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void doesNotLeakInternalMessagesToThePageUnderTest() { driver.get(appServer.whereIs("messages.html")); JavascriptExecutor executor = (JavascriptExecutor) driver; executor.executeScript("window.postMessage('hi', '*');"); long numMessages = (Long) executor.executeScript( "return window.messages.length;"); assertThat(numMessages).isEqualTo(1L); }
Example #20
Source File: AccountRestServiceCorsTest.java From keycloak with Apache License 2.0 | 5 votes |
private Result doJsPost(JavascriptExecutor executor, String url, String token, String data, boolean expectAllowed) { String js = "var r = new XMLHttpRequest();" + "var r = new XMLHttpRequest();" + "r.open('POST', '" + url + "', false);" + "r.setRequestHeader('Accept','application/json');" + "r.setRequestHeader('Content-Type','application/json');" + "r.setRequestHeader('Authorization','bearer " + token + "');" + "r.send('" + data + "');" + "return r.status + ':::' + r.responseText"; return doXhr(executor, js, expectAllowed); }
Example #21
Source File: AlertHandlingPageLoadListenerTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testAfterNavigateToAcceptAlert() { pageLoadListenerForAlertHanding.setAlertHandlingOptions(AlertHandlingOptions.ACCEPT); pageLoadListenerForAlertHanding.afterNavigateTo(URL, webDriver); verify((JavascriptExecutor) webDriver).executeScript(ALERT_SCRIPT, true); }
Example #22
Source File: JavascriptActionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void shouldScrollToTheEndOfWebElement() { WebElement webElement = mock(WebElement.class); javascriptActions.scrollToRightOf(webElement); verify((JavascriptExecutor) webDriver).executeScript("arguments[0].scrollLeft=arguments[0].scrollWidth;", webElement); }
Example #23
Source File: NavigationStepDefinitions.java From IridiumApplicationTesting with MIT License | 5 votes |
/** * Updates the location with the given hash. This is useful for manually navigating * around a single page application. * @param alias Add this word to indicate that the hash comes from an alias * @param hash The name of the hash */ @When("I go to the hash location( alias)? \"(.*?)\"") public void openHash(final String alias, final String hash) { final String hashValue = autoAliasUtils.getValue(hash, StringUtils.isNotBlank(alias), State.getFeatureStateForThread()); final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread(); ((JavascriptExecutor) webDriver).executeScript("window.location.hash='#" + hashValue + "'"); sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep()); }
Example #24
Source File: SeleniumWebDriver.java From che with Eclipse Public License 2.0 | 5 votes |
public void switchFromDashboardIframeToIde(int timeout) { wait(timeout).until(visibilityOfElementLocated(By.id("ide-application-iframe"))); wait(LOADER_TIMEOUT_SEC) .until( (ExpectedCondition<Boolean>) driver -> (((JavascriptExecutor) driver) .executeScript("return angular.element('body').scope().showIDE")) .toString() .equals("true")); wait(timeout).until(frameToBeAvailableAndSwitchToIt(By.id("ide-application-iframe"))); }
Example #25
Source File: GetEval.java From selenium with Apache License 2.0 | 5 votes |
@Override protected String handleSeleneseCommand(WebDriver driver, String locator, String value) { StringBuilder builder = new StringBuilder(); mutator.mutate(locator, builder); Object result = ((JavascriptExecutor) driver).executeScript(builder.toString()); return result == null ? "" : String.valueOf(result); }
Example #26
Source File: JavascriptActionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testExecuteScriptFromResource() { javascriptActions.executeScriptFromResource(JavascriptActions.class, SCROLL_TO_END_OF_PAGE); verify((JavascriptExecutor) webDriver) .executeScript(ResourceUtils.loadResource(JavascriptActions.class, SCROLL_TO_END_OF_PAGE)); }
Example #27
Source File: DragAndDropTest.java From selenium with Apache License 2.0 | 5 votes |
@SwitchToTopAfterTest @Test public void testDragAndDropToElementInIframe() { driver.get(pages.iframePage); final WebElement iframe = driver.findElement(By.tagName("iframe")); ((JavascriptExecutor) driver).executeScript("arguments[0].src = arguments[1]", iframe, pages.dragAndDropPage); driver.switchTo().frame(0); WebElement img1 = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test1"))); WebElement img2 = driver.findElement(By.id("test2")); new Actions(driver).dragAndDrop(img2, img1).perform(); assertThat(img2.getLocation()).isEqualTo(img1.getLocation()); }
Example #28
Source File: AlertHandlingPageLoadListenerTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testAfterNavigateForwardAcceptAlert() { pageLoadListenerForAlertHanding.setAlertHandlingOptions(AlertHandlingOptions.ACCEPT); pageLoadListenerForAlertHanding.afterNavigateForward(webDriver); verify((JavascriptExecutor) webDriver).executeScript(ALERT_SCRIPT, true); }
Example #29
Source File: GetAllWindowNames.java From selenium with Apache License 2.0 | 5 votes |
@Override protected String[] handleSeleneseCommand(WebDriver driver, String ignored, String alsoIgnored) { String current = driver.getWindowHandle(); List<String> attributes = new ArrayList<>(); for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle); attributes.add(((JavascriptExecutor) driver).executeScript("return window.name").toString()); } driver.switchTo().window(current); return attributes.toArray(new String[attributes.size()]); }
Example #30
Source File: ITCreateMultipleBuckets.java From nifi-registry with Apache License 2.0 | 5 votes |
@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); } }