How can I execute JS command using my chromedriver, inside a Java code?

mukesh.maki :

I would like to ask you how can I scroll into a web page by using a JS command. Though, I want this JS command inside a Java code-block. For the above purpose let me tell you that I also use Selenium framework. Is it possible?

The purpose is to do so by using Selenium and Java. I don't care about the general usage of JavascriptExecutor. I want their combination for SCROLL functionality!

dpapadopoulos :

I would like to answer in detail with all the possible scroll options because it is not determined in the question. So I give you below a practical and a theoretical answer. The first one to finish your job and the second one to read theory for future usages because there are many options about this theme.

Code sample:

import org.openqa.selenium.JavascriptExecutor; // packet that you need to import

WebDriver driver = new ChromeDriver(); // driver creation

JavascriptExecutor js = (JavascriptExecutor) driver; // giving to your driver the possibility to execute JS commands

js.executeScript("window.scrollBy(2000,1000)", ""); // scroll 2000 for x-coord and 1000 for y-coord
js.executeScript("window.scrollByPages(4)", ""); // scroll down the document by 4 pages
js.executeScript("window.scrollByPages(-4)", ""); // scroll up the document by 4 pages
js.executeScript("window.scrollByLines(10)", ""); // scroll down the document by 10 lines

WebElement toScrollElement = driver.findElement(By.XPATH_OR_ID_OR_OTHER("GIVEN_XPATH_OR_ID_OR_OTHER")); // locate the element you want to scroll into
js.executeScript("arguments[0].scrollIntoView(true);", toScrollElement); // scroll until the given element

Theory documentation:

I for one believe that the official documentation about this theme is included in the next links: here for scroll with Window options and here for scrolling with Element options. I am sure that more documentation from other sources exists too. I just present you sources from which I took the information.

Also, JavascriptExecutor has a second option which is the js.executeAsyncScript();. You can also read the documentation of JavascriptExecutor itself from here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146600&siteId=1