JavaScript Execution – Selenium WebDriver

JavaScript is a programming language of HTML which is used to program the behaviour of web pages.

JavaScript Executor:

Selenium WebDriver provides support to inject any JavaScript on a browser. JavaScriptExecutor is an interface which is used to execute JavaScript through Selenium WebDriver. It has two methods “executeScript” & “executeAsyncScript”  to run JavaScript.

Let us consider an example “Scroll Down Operation” using Selenium WebDriver:

Refer below code:

public void scrollPage(WebDriver Driver, int x, int y){
		String jsCommand;
		JavascriptExecutor jsEngine;
		
		oJSEngine = (JavascriptExecutor) Driver;
		
		jsCommand = String.format("window.scrollTo(%d, %d)", x,y);
		
		jsEngine.executeScript(jsCommand);
	}

In the above code, first we have defined a string variable “jsCommand” and another variable “jsEngine” of type javaScriptExecutor. jsCommand is initialised with the JavaScript to be executed, here in this example it is “window.scrollTo(<x-cordinate>, <y-cordinate>)” and jsEngine is used to run the command.

x and y coordinates are integer values, and their value is in pixels.

Practical Scenarios: Scroll down through a page after a product search on an ecommerce site:

Scenario:

  1. Open any browser of your choice say “Chrome.”
  2. Navigate to “http://www.ebay.in”.
  3. Search for a product say, “Apple watches” and select the category as “Watches” and click on Search button.
  4. A search operation is performed, and products are displayed on the page.
  5. Now scroll down to each product one by one and fetch its details.

Fetching the list using XPath locator

Refer the code below:

package day12;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

public class EbayProject {
	
	WebDriver Driver;
	
	
	public void invokeBrowser(String sBrowserType){
		
		
		switch (sBrowserType) {
		case "firefox":
			
			Driver = new FirefoxDriver();
			break;
			
		case "chrome":
		System.setProperty("webdriver.chrome.driver", "C:\\workspace\\libs\\chromedriver.exe");
			Driver = new ChromeDriver();
			break;
		case "ie":
			System.setProperty("webdriver.ie.driver", "C:\\workspace\\libs\\IEDriverServer.exe");
			Driver = new InternetExplorerDriver();
			break;

		default:
			System.out.println("Invalid BrowserType.. Setting default browser as Firefox..");
			Driver = new FirefoxDriver();
			break;
		}
		
		Driver.manage().window().maximize();
		
		Driver.manage().deleteAllCookies();
		
		Driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
		
		Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		
		Driver.get("http://www.ebay.in");
		
	}
	//--------------------------------------------------------------------------
	
	public String searchItem(String sProduct, String sCategory) throws InterruptedException{
		
		Driver.findElement(By.id("gh-ac")).sendKeys(sProduct);
		
		Select dropdown = new Select(Driver.findElement(By.id("gh-cat")));
		
		dropdown.selectByVisibleText(sCategory);
		
		Actions action = new Actions(Driver);
		
		Thread.sleep(3000);
		action.sendKeys(Keys.TAB);
		
		Thread.sleep(3000);
		action.sendKeys(Keys.ENTER);
		
		//Driver.findElement(By.id("gh-btn")).click();
		
		return Driver.findElement(By.className("listingscnt")).getText();
	}
	
	//----------------------------------------------------------------------------
	
	
	
	public void getAllProducJS(){
		List<WebElement> allProduct = Driver.findElements(By.xpath("//ul[@id='ListViewInner']/li"));
		
		for(WebElement product : allProduct){
			int X = product.getLocation().x;
			int Y = product.getLocation().y;
			
			scrollTo(X, Y);
			String sProduct = product.getText();
			
		//	String[] aProduct = sProduct.split("/n");
			System.out.println(sProduct);
			
			System.out.println("*********************************************");
		}
		
	}
	
	private void scrollTo(int x, int y){
		
		String jsCommand;
		JavascriptExecutor jsEngine;
		
		jsEngine = (JavascriptExecutor) Driver;
		
		jsCommand = String.format("window.scrollTo(%d,%d)", x, y);
		
		jsEngine.executeScript(jsCommand);
	}

}

This scenario is an extension of a scenario we saw earlier while learning “Working with Dropdown”You can refer to this tutorial for the explanation of first four steps. Let us focus on 5th step here. To scroll down to each product first, fetch the location (i.e. x and y coordinates) of each product (WebElement) one by one and then call scroll down method.

getLocation().x; – this will return x coordinate on the screen.

getLocation().y; – this will return y coordinate on the screen.

Both the above, integer values are then passed as an argument in the window.scrollTo(int x, int y) method and is iterated over a List which contains all the products as a WebElement using enhanced for loop.

scrollTo is the same method that we saw earlier in this article.

By getText() method, we can fetch the details of all the products.

Above example can be considered as a reference to execute any JavaScript scenario, the only thing which changes is jsCommand. Rest the code will remain same.

For any questions, queries or comments feel free to write us at support@qatechhub.com or saurabh@qatechub.com. Happy Learning ?

Saurabh Dhingra

About the Author

Saurabh Dhingra

Follow Saurabh Dhingra: