Given a site, AJAX components on the page and I need to wait till the whole page is fully loaded.
Here is my wait method using JavascriptExecutor checking document.readyState:
public void waitForLoading2() {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
if(!driver.findElements(By.xpath("//*[#id='wait'][contains(#style, 'display: block')]")).isEmpty()) {
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='wait'][contains(#style, 'display: none')]")));
}
ExpectedCondition<Boolean> expectation = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equalsIgnoreCase("complete");
}
};
wait.until(expectation);
}
Sometimes it's failing with the following Error msg:
org.openqa.selenium.JavascriptException: JavaScript error (WARNING:
The server did not provide any stacktrace information)
What did I miss here? My assumption is that document.readyState is common and always can be checked.
Thanks
There are more complex options, like this one
public static void waitForAjax(WebDriver driver, String action) {
driver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);
((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"var xhr = new XMLHttpRequest();" +
"xhr.open('POST', '/" + action + "', true);" +
"xhr.onreadystatechange = function() {" +
" if (xhr.readyState == 4) {" +
" callback(xhr.responseText);" +
" }" +
"};" +
"xhr.send();");
}
in order
to wait till the whole page is fully loaded
But the following did the trick for me - I check if there are ongoing AJAX calls and wait till those are done:
JavascriptExecutor js = (JavascriptExecutor) driverjs;
js.executeScript("return((window.jQuery != null) && (jQuery.active === 0))").equals("true");
Checking document.readyState will not help you with AJAX calls. Your best bet is to find an element in the area being loaded by AJAX and wait until it is visible. Then you'll know that the page is loaded. If there are multiple/separate areas loaded by AJAX calls, then you will want to pick an element from each area.
If you use jQuery to send AJAX request, you can get the value of jQuery.active. it's equivalent to all AJAX requests complete when jQuery.active=0.
Use executeScript("return jQuery.active==0"). For detail please read this artical
Related
I am trying to check if web page is loaded completed or not (i.e. checking that all the control is loaded) in selenium.
I tried below code:
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
but even if page is loading above code does not wait.
I know that I can check for particular element to check if its visible/clickable etc but I am looking for some generic solution
As you mentioned if there is any generic function to check if the page has completely loaded through Selenium the answer is No.
First let us have a look at your code trial which is as follows :
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
The parameter pageLoadTimeout in the above line of code doesn't really reseambles to actual pageLoadTimeout().
Here you can find a detailed discussion of pageLoadTimeout in Selenium not working
Now as your usecase relates to page being completely loaded you can use the pageLoadStrategy() set to normal [ the supported values being none, eager or normal ] using either through an instance of DesiredCapabilities Class or ChromeOptions Class as follows :
Using DesiredCapabilities Class :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class myDemo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
DesiredCapabilities dcap = new DesiredCapabilities();
dcap.setCapability("pageLoadStrategy", "normal");
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dcap);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
System.out.println(driver.getTitle());
driver.quit();
}
}
Using ChromeOptions Class :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.PageLoadStrategy;
public class myDemo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
FirefoxOptions opt = new FirefoxOptions();
opt.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
System.out.println(driver.getTitle());
driver.quit();
}
}
You can find a detailed discussion in Page load strategy for Chrome driver (Updated till Selenium v3.12.0)
Now setting PageLoadStrategy to NORMAL and your code trial both ensures that the Browser Client have (i.e. the Web Browser) have attained 'document.readyState' equal to "complete". Once this condition is fulfilled Selenium performs the next line of code.
You can find a detailed discussion in Selenium IE WebDriver only works while debugging
But the Browser Client attaining 'document.readyState' equal to "complete" still doesn't guarantees that all the JavaScript and Ajax Calls have completed.
To wait for the all the JavaScript and Ajax Calls to complete you can write a function as follows :
public void WaitForAjax2Complete() throws InterruptedException
{
while (true)
{
if ((Boolean) ((JavascriptExecutor)driver).executeScript("return jQuery.active == 0")){
break;
}
Thread.sleep(100);
}
}
You can find a detailed discussion in Wait for ajax request to complete - selenium webdriver
Now, the above two approaches through PageLoadStrategy and "return jQuery.active == 0" looks to be waiting for indefinite events. So for a definite wait you can induce WebDriverWait inconjunction with ExpectedConditions set to titleContains() method which will ensure that the Page Title (i.e. the Web Page) is visible and assume the all the elements are also visible as follows :
driver.get("https://www.google.com/");
new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("partial_title_of_application_under_test"));
System.out.println(driver.getTitle());
driver.quit();
Now, at times it is possible though the Page Title will match your Application Title still the desired element you want to interact haven't completed loading. So a more granular approach would be to induce WebDriverWait inconjunction with ExpectedConditions set to visibilityOfElementLocated() method which will make your program wait for the desired element to be visible as follows :
driver.get("https://www.google.com/");
WebElement ele = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath_of_the_desired_element")));
System.out.println(ele.getText());
driver.quit();
References
You can find a couple of relevant detailed discussions in:
Selenium IE WebDriver only works while debugging
Selenium how to manage wait for page load?
I use selenium too and I had the same problem, to fix that I just wait also for the jQuery to load.
So if you have the same issue try this also
((Long) ((JavascriptExecutor) browser).executeScript("return jQuery.active") == 0);
You can wrap both function in a method and check until both page and jQuery is loaded
Implement this, Its working for many of us including me. It includes Web Page wait on JavaScript, Angular, JQuery if its there.
If your Application is containing Javascript & JQuery you can write code for only those,
By define it in single method and you can Call it anywhere:
// Wait for jQuery to load
{
ExpectedCondition<Boolean> jQueryLoad = driver -> ((Long) ((JavascriptExecutor) driver).executeScript("return jQuery.active") == 0);
boolean jqueryReady = (Boolean) js.executeScript("return jQuery.active==0");
if (!jqueryReady) {
// System.out.println("JQuery is NOT Ready!");
wait.until(jQueryLoad);
}
wait.until(jQueryLoad);
}
// Wait for ANGULAR to load
{
String angularReadyScript = "return angular.element(document).injector().get('$http').pendingRequests.length === 0";
ExpectedCondition<Boolean> angularLoad = driver -> Boolean.valueOf(((JavascriptExecutor) driver).executeScript(angularReadyScript).toString());
boolean angularReady = Boolean.valueOf(js.executeScript(angularReadyScript).toString());
if (!angularReady) {
// System.out.println("ANGULAR is NOT Ready!");
wait.until(angularLoad);
}
}
// Wait for Javascript to load
{
ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString()
.equals("complete");
boolean jsReady = (Boolean) js.executeScript("return document.readyState").toString().equals("complete");
// Wait Javascript until it is Ready!
if (!jsReady) {
// System.out.println("JS in NOT Ready!");
wait.until(jsLoad);
}
}
Click here for Reference Link
Let me know if you stuck anywhere by implementing.
It overcomes the use of Thread or Explicit Wait.
public static void waitForPageToLoad(long timeOutInSeconds) {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
try {
System.out.println("Waiting for page to load...");
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeOutInSeconds);
wait.until(expectation);
} catch (Throwable error) {
System.out.println(
"Timeout waiting for Page Load Request to complete after " + timeOutInSeconds + " seconds");
}
}
Try this method
This works for me well with dynamically rendered websites:
Wait for complete page to load
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
Make another implicit wait with a dummy condition which would always fail
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + "This text will always fail :)" + "')]"))); // condition you are certain won't be true
}
catch (TimeoutException te) {
}
Finally, instead of getting the html source - which would in most of one page applications would give you a different result , pull the outerhtml of the first html tag
String script = "return document.getElementsByTagName(\"html\")[0].outerHTML;";
content = ((JavascriptExecutor) driver).executeScript(script).toString();
There is a easy way to do it. When you first request the state via javascript, it tells you that the page is complete, but after that it enters the state loading. The first complete state was the initial page!
So my proposal is to check for a complete state after a loading state. Check this code in PHP, easily translatable to another language.
$prevStatus = '';
$checkStatus = function ($driver) use (&$prevStatus){
$status = $driver->executeScript("return document.readyState");
if ($prevStatus=='' && $status=='loading'){
//save the previous status and continue waiting
$prevStatus = $status;
return false;
}
if ($prevStatus=='loading' && $status=='complete'){
//loading -> complete, stop waiting, it is finish!
return true;
}
//continue waiting
return false;
};
$this->driver->wait(20, 150)->until($checkStatus);
Checking for a element to be present also works well, but you need to make sure that this element is only present in the destination page.
Something like this should work (please excuse the python in a java answer):
idle = driver.execute_async_script("""
window.requestIdleCallback(() => {
arguments[0](true)
})
""")
This should block until the event loop is idle which means all assets should be loaded.
According to a number of articles I have seen, the use of Thread.sleep() seems to be frowned upon. I have used this frequently in my test classes, where it was necessary to wait for something to load. I have tried using this method to tell me when load is complete, but that did not help. It is not a reliable method.:
try {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
|| ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
} catch (Exception e) {
System.err.println(thisClass + " Exception caught: " + e.getMessage());
}
What alternatives methods can I use?
This solution worked:
Calling function:
String className = "gwt-Button form-control btn back-button ripple-container";
String textToFind = "back-button-icon";
String htmlElement = "button";
boolean isReady = Common.FluentWait(driver, 60, className, textToFind, htmlElement);
That function:
public static boolean FluentWait(WebDriver driver, int timeOut, String className, String textToFind,
String htmlElement) {
// Waiting timeOut seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Common.myPrint(thisClass + " FluentWait. ");
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(timeOut, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
Common.myPrint(thisClass + " run returnWebElement. ");
return returnWebElement(className, textToFind, htmlElement, driver);
}
});
if (foo != null) {
return true;
}
return false;
}
and the function I called inside that:
public static WebElement returnWebElement(String className, String textToFind, String htmlElement,
WebDriver driver) {
List<WebElement> elements = Common.findElementsUsingHtmlXpathClass(driver, htmlElement, className);
Common.myPrint(thisClass + " elements count: " + elements.size());
String text = "";
for (WebElement element : elements) {
// select an element
if (element.isDisplayed()) {
text = element.getAttribute("innerHTML");
if (text != "") {
text = text.trim();
if (text.contains(textToFind)) {
Common.myPrint(thisClass + " innerHTML: " + text);
Common.myPrint(thisClass + " returning element found. ");
return element;
}
}
}
}
Common.myPrint(thisClass + " element not found. ");
return null;
}
You can use FluentWait
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
/*
code snippet will Wait 30 seconds for
an element to be present on the page and check for its
presence once every 5 seconds.
*/
Wait wait = new FluentWait(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
another wait also available
I have found another way although it is very similar to Thread.sleep(). I was looking for another wait as the implicit wait and explicit wait with Selenium is not waiting long enough for me.
The alternative I used:
TimeUnit.SECONDS.sleep(int timeUnit)
This delivered the same functionality as Thread.sleep(). I hope this helps.
Your code will just attempt to wait for the page to load, not wait for specific elements, etc. to load. This will work fine for static HTML pages but once you start adding dynamic sections to the page (using AJAX, etc.) , it will not accomplish what you want.
You can use WebDriverWait. See the docs for more info.
Simple example,
// create an instance that can be reused
WebDriverWait wait = new WebDriverWait(driver, 10);
// wait for an element to be clickable and store the return
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("someId"));
// click the returned button
button.click();
There are a bunch of standard conditions provided by ExpectedConditions. See the docs for more info.
I am trying to validate while class attribute contains "ng-hide", the Section will not display on the web app. And I am trying to verify
"Element=//*[#id='index-13'][#class='col-3 uib-tab nav-item ng-scope ng-isolate-scope ng-hide']" does not exist with the code below:
WebElement We = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Element)));
Assert.assertFalse(We.isDisplayed(), strScenarioName + ":# WebElement '" + Element + "' is not Exist Validation. Element(s) is displayed: " + We.isDisplayed());
Here is the DOM :
<li id="index-13" class="col-3 uib-tab nav-item ng-scope ng-isolate-scope ng-hide" ng-class="[{active: active, disabled: disabled}, classes]" ng-click="claims.chargelineDetailCall('Section Indicator')" ng-show="claims.isApprovedClaim()" heading="Benefit Indicators" index="13">
<a class="nav-link ng-binding" uib-tab-heading-transclude="" ng-click="select($event)" href="">Section Indicator</a>
I am getting below error:
org.openqa.selenium.TimeoutException: Timed out after 60 seconds waiting for visibility of element located by By.xpath: //*[#id='index-13'[#class='col-3 uib-tab nav-item ng-scope ng-isolate-scope ng-hide']
Build info: version: '2.53.1',
Note: I tried with By.id, By.cssSelector, By.name and so on but nothing is working. Please advise me how to over come the situation
Instead of using a whole lot of classes in your xpath, you could've use the #contains() method to see if the <li> is actually visible.
I think your xpath should look like this -
element = WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.XPATH, "//li[contains(#class,'ng-hide') and #contains(#id,13)")))
//include your assert statement here.
This code is in Python, however, you can use the XPATH locator and use it in your script.
Assuming that the element can be found using "//li[#id='index-13']"
By elementBy = By.xpath("//li[#id='index-13']");
If(driver.findElement(elementBy).getAttributes("class").contains("ng-hide")){
Assert.assertTrue(true,waitForInvisibilityOfWebElement(driver, elementBy ));
}
public static boolean waitForInvisibilityOfWebElement(WebDriver driver, By locator){
boolean result = false;
System.out.println("Fluently waiting for invisibility of element with locator: " +locator.toString());
try {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
result = true;
} catch(TimeoutException e) {
System.out.println("TimeoutException occurred while waiting for invisibility of element " +locator.toString()+ " : " +e.getMessage());
result = false;
}
return result;
}
I'm trying get for page to load completely before doing an action. I don't want to start an action while loading circle on the browser tab is still turning. My wait for ajax function is not working for some cases, especially for new page loading. My function is JQuery based:
JavascriptExecutor jsDriver = (JavascriptExecutor) webDriver;
boolean stillRunningAjax = (Boolean) jsDriver
.executeScript("return window.jQuery != undefined && jQuery.active != 0");
return !stillRunningAjax;
if that comes false, running it again.
But for page loading, after it returns true, browser is still loading (loading circle is turning) for a couple of seconds more (sometimes much more).
I've tried implicitlyWait but it stops the function at the same time with my function.
Some says there is not a complete solution for this in selenium. But there should be. Maybe a JavaScript included solution, anything.
Using javascript to wait for page to load:
void waitForLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
If you're waiting for an ajax to display an element on page, you can wait for the element itself.
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
I want to use JavaScript with WebDriver (Selenium 2) using Java.
I've followed some a guide and on Getting Started page: there is an instruction at 1st line to run as:
$ ./go webdriverjs
My question: From which folder/location the command mentioned above will be run/executed?
Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver. Please correct me if I'm wrong.
The WebDriverJs is actually "just" another WebDriver language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.
If you want to run JavaScript code in Java WebDriver, do this instead:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
I like to do this, also:
WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
} // else throw...
// later on...
js.executeScript("return document.getElementById('someId');");
You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor.
The executeScript() takes function calls and raw JS, too. You can return a value from it and you can pass lots of complicated arguments to it, some random examples:
1.
// returns the right WebElement
// it's the same as driver.findElement(By.id("someId"))
js.executeScript("return document.getElementById('someId');");
// draws a border around WebElement
WebElement element = driver.findElement(By.anything("tada"));
js.executeScript("arguments[0].style.border='3px solid red'", element);
// changes all input elements on the page to radio buttons
js.executeScript(
"var inputs = document.getElementsByTagName('input');" +
"for(var i = 0; i < inputs.length; i++) { " +
" inputs[i].type = 'radio';" +
"}" );
JavaScript With Selenium WebDriver
Selenium is one of the most popular automated testing suites.
Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.
public static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver(); // This opens a window
String url = "----";
/*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
driver.findElement(By.name("j_password")).sendKeys("yashwanth#123");*/
JavascriptExecutor jse = (JavascriptExecutor) driver;
if (jse instanceof WebDriver) {
//Launching the browser application
jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[#name='j_password']")).sendKeys("admin");
//Opend Site and click on some links. then you can apply go(-1)--> back forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();
jse.executeScript("window.history.go(0)");
jse.executeScript("window.history.go(-2)");
jse.executeScript("window.history.forward(-2)");
String title = (String)jse.executeScript("return document.title");
System.out.println(" Title Of site : "+title);
String domain = (String)jse.executeScript("return document.domain");
System.out.println("Web Site Domain-Name : "+domain);
// To get all NodeList[1052] document.querySelectorAll('*'); or document.all
jse.executeAsyncScript("document.getElementsByTagName('*')");
String error=(String) jse.executeScript("return window.jsErrors");
System.out.println("Windowerrors : "+error);
System.out.println("To Find the input tag position from top");
ArrayList<?> al = (ArrayList<?>) jse.executeScript(
"var source = [];"+
"var inputs = document.getElementsByTagName('input');"+
"for(var i = 0; i < inputs.length; i++) { " +
" source[i] = inputs[i].offsetParent.offsetTop" + //" inputs[i].type = 'radio';"
"}"+
"return source"
);//inputs[i].offsetParent.offsetTop inputs[i].type
System.out.println("next");
System.out.println("array : "+al);
// (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys
Keys k = null;
String selectAll = Keys.chord(Keys.CONTROL, "a");
WebElement body = driver.findElement(By.tagName("body"));
body.sendKeys(selectAll);
// Search for text in Site. Gets all ViewSource content and checks their.
if (driver.getPageSource().contains("login")) {
System.out.println("Text present in Web Site");
}
Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
System.out.println("Client Body Height : "+clent_height);
// using selenium we con only execute script but not JS-functions.
}
driver.quit(); // to close browser
}
To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.
Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
String js_TxtFile = "";
while (sc.hasNext()) {
String[] s = sc.next().split("\r\n");
for (int i = 0; i < s.length; i++) {
js_TxtFile += s[i];
js_TxtFile += " ";
}
}
String title = (String) jse.executeScript(js_TxtFile);
System.out.println("Title : "+title);
document.title & document.getElementById() is a property/method available in Browsers.
JsFile.txt
var title = getTitle();
return title;
function getTitle() {
return document.title;
}
You can also try clicking by JavaScript:
WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);
Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.
I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here.
How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.
driver.executeScript("function(arguments[0]);","parameter to send in");
If you want to read text of any element using javascript executor, you can do something like following code:
WebElement ele = driver.findElement(By.xpath("//div[#class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);
In this example, I have following HTML fragment and I am reading "156".
<div class="infaCompositeViewTitle">
<span>All Assets</span>
<span>156</span>
</div>
Following code worked for me:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
public class SomeClass {
#Autowired
private WebDriver driver;
public void LogInSuperAdmin() {
((JavascriptExecutor) driver).executeScript("console.log('Test test');");
}
}
I had a similar situation and solved it like this:
WebElement webElement = driver.findElement(By.xpath(""));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
You need to run this command in the top-level directory of a Selenium SVN repository checkout.