Selenium WebDriver resize textarea - resize

Using Selenium webdriver with Java how can I resize a textarea/
I want to expand the textarea by dragging the right-bottom corner of the element.
I have tried something like this, but it doesnt change the element at all
new Actions(webdriver).dragAndDropBy(element, height, width).perform()

I do not have anything to test this issue on, but i'm guessing the reason the dragAndDropBy method you used didn't work because it would not be clicking the bottom-right corner of the element. I believe you would need something like:
Actions action = new Actions(driver);
action.moveToElement(toElement, xOffset, yOffset); //moves to bottom right corner
action.clickAndHold();
action.moveByOffset(xOffset, yOffset);
action.release();
action.perform();
The offsets depend on the size of the text area you mentioned. You can look into more on the Action class at: http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html. Hopefully this helps.

I think the reason your code was not working because build() method was not included can you try this and tell if its now working-
new Actions(webdriver).dragAndDropBy(element, height, width).build().perform();

This can be done with JavaScriptExecutor interface. JavaScriptExecutor is an interface which provides mechanism to execute Javascript through selenium webdriver with the help of this you can change rows and cols attributes of textarea hence textarea can be resize with it. Hope this will help you out -
public static void main(String[] args) {
ProfilesIni profile = new ProfilesIni();
FirefoxProfile a = profile.getProfile("default");
WebDriver driver = new FirefoxDriver(a);
driver.get("http://localhost/testfolder/textarea.html");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('textarea').setAttribute('rows', '30')");
js.executeScript("document.getElementById('textarea').setAttribute('cols', '50')");
}
just locate textarea element with an element locator then set 'rows' and 'cols' attribute values.
I hope this helps you.

Related

How to click on save button in chrome print privew page using selenium Java

I am currently looking for a solution to click on Sava button in chrome print preview window with selenium Java.
Is there any way we can handel chrome print preview page?
I have tried with the Robot class, but it seems not reliable/stable for my application.
Could you please someone help me to achieve this with selenium Java.
I fail to see any "Save" button on print preview page for Chrome browser
Here is how you can click "Cancel" button, I believe you will be able to amend the code to match your requirements:
First of all make sure to wait for the preview page to be available using Explicit Wait
Change the context to the print preview window via WebDriver.switchTo() function
All the elements at the print preview page are hidden in ShadowDom therefore you will need to:
Locate the element which is the first parent of the element you're looking for
Get its ShadowRoot property and cast the result to a WebElement
Use the WebElement.findElement() function to locate the next parent
repeat above steps until you reach the desired button
Example code just in case:
new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
driver.switchTo().window(driver.getWindowHandles().stream().skip(1).findFirst().get());
WebElement printPreviewApp = driver.findElement(By.tagName("print-preview-app"));
WebElement printPreviewAppConten = expandShadowRoot(printPreviewApp, driver);
WebElement printPreviewSidebar = printPreviewAppConten.findElement(By.tagName("print-preview-sidebar"));
WebElement printPreviewSidebarContent = expandShadowRoot(printPreviewSidebar, driver);
WebElement printPreviewHeader = printPreviewSidebarContent.findElement(By.tagName("print-preview-header"));
WebElement printPreviewHeaderContent = expandShadowRoot(printPreviewHeader, driver);
printPreviewHeaderContent.findElements(By.tagName("paper-button")).get(1).click();
where expandShadowRoot function looks like:
private WebElement expandShadowRoot(WebElement parent, WebDriver driver) {
return (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0].shadowRoot", parent);
}
Save button will not work because page is not part of webpage. selenium only support web based application.
But you can use SIKULI to handle above scenario.

Selenium click not work

Help me please.
Selenium does not click on element and element is clickable(selenium does not generate exception).
I try use Id, css, xpath locators, nothing did not help me.
What should i do to decide my problem?
Java code example.
WebElement sector = webDriver.findElement(By.id("sector-1"));
sector.click();
After click system must open this page
Seems that you try to interact with object inside a <svg> element. If so, you cannot manage it's child elements simply using click() method.
Try this instead:
WebElement svgObject = driver.findElement(By.xpath("//polygon[#id='sector-1:canvas']"));
Actions builder = new Actions(driver);
builder.click(svgObject).build().perform();
Use below XPath :
WebElement sector = webDriver.findElement(By.xpath("//g[#id='sector-1']/polygon"));
sector.click();
OR
WebElement sector = webDriver.findElement(By.xpath("//polygon[#id='sector-1:canvas']"));
sector.click();
I decide my problem.
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"sector-2:canvas\"]")));
WebElement svgObject = webDriver.findElement(By.xpath("//*[#id=\"sector-2:canvas\"]"));
Actions builder = new Actions(webDriver);
builder.click(svgObject).build().perform();

Popup scroll not working in selenium webdriver

I am running my script in mozilla firefox I want to scroll popup I
applied so many methods but doesn't work for me
I used keys.tab to reach that element but it was unable to enter text in that textfield using senkeys("xyz#gmail.com)
I used scroll method
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('youama-email').scrollIntoView(true);");
some exception occur
3.I used Moveto element method but got exception
WebElement element = driver.findElement(By.id("youama-email"));
Actions
actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.perform();
// Initialize Javascript executor
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll inside web element vertically (e.g. 100 pixel)
js.executeScript("arguments[0].scrollTop =
arguments[1];",driver.findElement(By.id("<div-id>")), 100);
Please help me to scroll and enter into the email as well as other
fields that will appear after scroll [![enter image description
here][1]][1]
[1]: http://i.stack.imgur.com/D0hqI.png
Try this code. I think what you didn't do was to wait for the element to be visible which i did. See the below code. It is running correctly.
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://wyomingvapor.com/");
driver.findElement(By.xpath(".//*[#id='header']/div/div[2]/div/a[1]")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='y-to-register']/input")));
driver.findElement(By.xpath(".//*[#id='y-to-register']/input")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='youama-firstname']")));
driver.findElement(By.xpath(".//*[#id='youama-firstname']")).sendKeys("xyz#gmail.com");
Thread.sleep(2000L);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_X);
robot.keyRelease(KeyEvent.VK_X);
robot.keyPress(KeyEvent.VK_Y);
robot.keyRelease(KeyEvent.VK_Y);
robot.keyPress(KeyEvent.VK_Z);
robot.keyRelease(KeyEvent.VK_Z);
If you still stuck then do reply to me, Jyotsana.
Happy Learning :-)

Selenium WebDriver zoom in/out page content

How to change page zoom level in Selenium WebDriver?
I tried:
driver.Keyboard().pressKey(Keys.Control);
driver.Keyboard().pressKey(Keys.Add);
But it doesn't work.
Beware that Selenium assumes the zoom level is at 100%! For example, IE will refuse to start (throws an Exception) when the zoom level is different, because the element locating depends on this and if you changed the zoom level, it would click on wrong elements, at wrong places.
Java
You can use the Keys.chord() method:
WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
Use cautiously and when you're done, reset the zoom back to 100%:
html.sendKeys(Keys.chord(Keys.CONTROL, "0"));
C#
(since I realized C# bindings don't have the Keys.chord() method)
Or, you can use the Advanced User Interactions API like this (again, Java code, but it should work the same in C#):
WebElement html = driver.findElement(By.tagName("html"));
new Actions(driver)
.sendKeys(html, Keys.CONTROL, Keys.ADD, Keys.NULL)
.perform();
Again, don't forget to reset the zoom afterwards:
new Actions(driver)
.sendKeys(html, Keys.CONTROL, "0", Keys.NULL)
.perform();
Note that the naïve approach
html.sendKeys(Keys.CONTROL, Keys.ADD);
doesn't work, because the Ctrl key is released in this sendKeys() method. The WebElement's sendKeys() is different from the one in Actions. Because of this, the Keys.NULL used in my solution is required.
Here are two ways the zoom level can be altered with Java (one is for Chrome and the other is for Firefox):
Chrome
When using v̲e̲r̲s̲i̲o̲n̲ ̲3̲.̲3̲.̲1 of the Selenium Java Client Driver and C̲h̲r̲o̲m̲e̲D̲r̲i̲v̲e̲r̲ ̲2̲.̲2̲8, the following works (where the number in single quotes represents the zoom level to use; 1 = 100%, 1.5 = 150%, etc.):
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.body.style.zoom = '1.5'");
Firefox
The zoom level can be modified with the following:
1. The aforementioned Java Client Driver
2. G̲e̲c̲k̲o̲D̲r̲i̲v̲e̲r̲ ̲v̲0̲.̲1̲5̲.̲0
3. These classes:
java.awt.Robot
java.awt.event.KeyEvent
First of all, instantiate the Robot class:
Robot robot = new Robot();
This code causes the zoom level to decrease:
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_MINUS);
This code causes the zoom level to increase:
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_EQUALS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_EQUALS);
Python approach working for me, except you have to specify the zoom level:
driver.execute_script("document.body.style.zoom='zoom %'")
Have 'zoom%' = whatever zoom level you want. (e.g. '67%'). This works for Chromedriver, which doesn't seem to accept the send_keys commands.
Zoom in | Zoom out Feature on Windows
Zoom in
WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
Zoom out
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
Zoom in | Zoom out Feature on MAC
Zoom in
WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.COMMAND, Keys.ADD));
Zoom out
html.sendKeys(Keys.chord(Keys.COMMAND, Keys.SUBTRACT));
The most robust approach
Before you start with Internet Explorer and Selenium Webdriver Consider these two important rules.
The zoom level :Should be set to default (100%) and
The security zone settings : Should be same for all. The security settings should be set according to your organisation permissions.
How to set this?
Simply go to Internet explorer, do both the stuffs manually. Thats it. No secret.
Do it through your code.
Method 1:
//Move the following line into code format
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver(capabilities);
driver.get(baseURl);
//Identify your elements and go ahead testing...
This will definetly not show any error and browser will open and also will navigate to the URL.
BUT This will not identify any element and hence you can not proceed.
Why? Because we have simly suppressed the error and asked IE to open and get that URL. However Selenium will identify elements only if the browser zoom is 100% ie. default. So the final code would be
Method 2 The robust and full proof way:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver(capabilities);
driver.get(baseURl);
driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,"0"));
//This is to set the zoom to default value
//Identify your elements and go ahead testing...
Hope this helps. Do let me know if further information is required.
Below snippet will set the browser zoom to 80%
String zoomJS;
JavascriptExecutor js = (JavascriptExecutor) driver;
zoomJS = "document.body.style.zoom='0.8'";
js.executeScript(zoomJS);
I know this is late, but in case if you don't want to use action class (or getting any errors, as I did) you can use pure JavaScript to do so.
Here is the code
((IJavaScriptExecutor) Browser.Driver).ExecuteScript("document.body.style.zoom = '70%';");
For Zoom In to 30%(or any other value you wish but in my case 30%) use
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.body.style.zoom = '30%';");
I am using Python 3.5.; I got the same problem as you. I thought you must use Chrome as browser.
I used PhantomJs to finally solve this problem:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
browser = webdriver.PhantomJS()
browser.get('http://www.*.com')
print(browser.title)
c=browser.find_element_by_tag_name("body")
c.send_keys(Keys.LEFT_CONTROL+Keys.Add)`
you may use "Keys.chord" method for Zoom out and Zoom in
Zoom OUT
WebElement zoomPage = driver.findElement(By.tagName("html"));
zoomPage.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD))
when you are done with your work and want to reset browser back to 100% then use below code
If you want to click on any element, so before click event you may reset you browser window to 100 % after you may click on it.
zoomPage.sendKeys(Keys.chord(Keys.CONTROL, "0"));
You may user Java script code as well for Zoom OUT
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.body.style.zoom = '110%'");
Changing the zoom level through javascript execution is OK but it only apply to the first page displayed. The succeeding pages will return to 100% zoom level.
The best solution I found so far is to set the Chrome Options' device scale factor.
ChromeOptions options = new ChromeOptions();
options.addArguments("force-device-scale-factor=0.75");
options.addArguments("high-dpi-support=0.75");
WebDriver driver = new ChromeDriver(options);
Seems that approach proposed for C# doesn't work anymore.
Approach for C# that works for me in WebDriver version 2.5 is:
public void ZoomIn()
{
new Actions(Driver)
.SendKeys(Keys.Control).SendKeys(Keys.Add)
.Perform();
}
public void ZoomOut()
{
new Actions(Driver)
.SendKeys(Keys.Control).SendKeys(Keys.Subtract)
.Perform();
}
Using Robot class worked for me:
for(int i=0; i<3; i++){
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_MINUS);
}
this will zoom out 3 times.
11-17-2017 Update
var html = page.FindElement(By.XPath("/html"));
html.SendKeys(Keys.Control + "0" + Keys.Control);
You can use Selenium's driver to execute a script that will zoom in or out for you.
Firefox
await driver.executeScript('document.body.style.MozTransform = "scale(3)"');
await driver.executeScript(
'document.body.style.MozTransformOrigin = "top"'
);
This will result in zooming in by 300% and will scroll to top.
Chrome
await driver.executeScript('document.body.style.zoom = "300%"');

Scroll Element into View with Selenium

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?
The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution is to scroll the item into view.
Have tried many things with respect to scroll, but the below code has provided better results.
This will scroll until the element is in view:
WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
//do anything you want with the element
You can use the org.openqa.selenium.interactions.Actions class to move to an element.
Java:
WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
Python:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250,350)");
You may want to try this.
If you want to scroll on the Firefox window using the Selenium webdriver, one of the ways is to use JavaScript in the Java code. The JavaScript code to scroll down (to bottom of the web page) is as follows:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
Targeting any element and sending down keys (or up/left/right) seems to work also. I know this is a bit of a hack, but I'm not really into the idea of using JavaScript to solve the scrolling problem either.
For example:
WebElement.sendKeys(Keys.DOWN);
In Selenium we need to take the help of a JavaScript executor to scroll to an element or scroll the page:
je.executeScript("arguments[0].scrollIntoView(true);", element);
In the above statement element is the exact element where we need to scroll. I tried the above code, and it worked for me.
I have a complete post and video on this:
http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/
webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);
For more examples, go here. All in Russian, but Java code is cross-cultural :)
I found that the bounding rect of my element was not correct, leading to the browser scrolling well off the screen. However, the following code works rather well for me:
private void scrollToElement(WebElement webElement) throws Exception {
((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
Thread.sleep(500);
}
You can use this code snippet to scroll:
C#
var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();
There you have it
This worked for me:
IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.
From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).
I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;
class Element
#
# Alias the original click method to use later on
#
alias_method :base_click, :click
# Override the base click method to scroll into view if the element is not visible
# and then retry click
#
def click
begin
base_click
rescue Selenium::WebDriver::Error::ElementNotVisibleError
location_once_scrolled_into_view
base_click
end
end
The 'location_once_scrolled_into_view' method is an existing method on WebElement class.
I apreciate you may not be using Ruby but it should give you some ideas.
The Ruby script for scrolling an element into view is as below.
$driver.execute_script("arguments[0].scrollIntoView(true);", element)
sleep(3)
element.click
Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.
Scrolling to the element happens implicitly so you just need to find the item and then work with it.
Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.
For scrolling down:
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0, 250)", "");
Or, also
js.executeScript("scroll(0, 250);");
For scrolling up:
js.executeScript("window.scrollBy(0,-250)", "");
Or,
js.executeScript("scroll(0, -250);");
This is a repeated solution with JavaScript, but with an added waiting for element.
Otherwise ElementNotVisibleException may appear if some action on the element is being done.
this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));
I have used this way for scrolling the element and click:
List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(#src,'image/plus_btn.jpg')]"));
for (WebElement clickimg : image)
{
((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);
clickimg.click();
}
def scrollToElement(element: WebElement) = {
val location = element.getLocation
driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}
Something that worked for me was to use the Browser.MoveMouseToElement method on an element at the bottom of the browser window. Miraculously it worked in Internet Explorer, Firefox, and Chrome.
I chose this over the JavaScript injection technique just because it felt less hacky.
You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FirefoxDriver ff = new FirefoxDriver();
ff.get("http://toolsqa.com");
Thread.sleep(5000);
ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
}
If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.
When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\_(ツ)_/¯
try
{
element.Click();
}
catch {
element.Click();
}
In most of the situation for scrolling this code will work.
WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));
js.executeScript("arguments[0].click();",element);
JAVA
Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".
Following import:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
First you need get x y location the element.
//initialize element
WebElement element = driver.findElement(By.id("..."));
//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();
//scroll to x y
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");
I am not sure if the question is still relevant but after referring to scrollIntoView documentation from https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.
The easiest solution would be
executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);
This scrolls the element into center of the page.
Javascript
The solustion is simple:
const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.
Here is my solution for Java:
public List<String> getBoundedRectangleOfElement(WebElement we)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
List<String> bounds = (ArrayList<String>) je.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
System.out.println("top: " + bounds.get(1));
return bounds;
}
And then, to scroll, you call it like this:
public void scrollToElementAndCenterVertically(WebElement we)
{
List<String> bounds = getBoundedRectangleOfElement(we);
Long totalInnerPageHeight = getViewPortHeight(driver);
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}
I've been doing testing with ADF components and you have to have a separate command for scrolling if lazy loading is used. If the object is not loaded and you attempt to find it using Selenium, Selenium will throw an element-not-found exception.
If nothing works, try this before clicking:
public void mouseHoverJScript(WebElement HoverElement) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
}
In Java we can scroll by using JavaScript, like in the following code:
driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");
You can assign a desired value to the "elm.scrollTop" variable.
A solution is:
public void javascriptclick(String element)
{
WebElement webElement = driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", webElement);
System.out.println("javascriptclick" + " " + element);
}