9aa. WebDriver – Executing JavaScript code

Hiya Champs! Let’s have some quality interaction with the browser today!! So, can you guess the language that is preferred by the browser? Yes, you got that right. It is JavaScript indeed. If you are using Chrome, clicking on ‘F12’ will open the ‘Developer Tools’ which helps us to execute JavaScript directly from the browser. Certain actions such as scrolling, displaying alerts etc. become a lot easier to manage with JavaScript.

Executing JavaScript in browser

Apart from this, there can also be other situations where we might not find the right Selenium API to do a particular action. But we might be able to perform that by executing JavaScript code. Selenium WebDriver provides an interface that helps us do just that!

JavascriptExecutor… you have heard it, it’s like those celebrities that are pretty famous. Well, it is time for us to go and meet the shining star. JavascriptExecutor does not need any external JAR files or plugins to be added. Just a single package import would do the job, “import org.openqa.selenium.JavascriptExecutor”. It has two important methods to execute JavaScript code from our Selenium test to automate the application under test, viz.,

  • executeScript(script, args)
  • executeAsyncScript(script, args)

JavascriptExecutor methods

Let us understand this in a couple simple steps.

Step 1:

Import the following package,  import org.openqa.selenium.JavascriptExecutor;

Create a JavascriptExecutor object and assign the driver object by typecasting it to JavascriptExecutor.

// Typecast driver to JavascriptExecutor
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;

Step 2:

The JavascriptExecutor object thus created allows us to execute JavaScript code from within the Selenium test.

// Scroll down by 100 pixels

This “excuteScript” method takes two arguments. First one is the JavaScript code and the second one is an optional list of arguments that the java script code requires.

Overall picture

Let us see a test case implementing the technique covered so far,


  1. Open Firefox browser
  2. Navigate to the demo site (https://chandanachaitanya.github.io/selenium-practice-site/)
  3. Print page URL to console with and without using JavaScript code
  4. Scroll the page vertically down by 100 pixels
  5. Refresh the page
  6. Navigate to the Google homepage
  7. Perform the above three actions using JavaScript code
  8. Verify Eclipse IDE console output screen and JUnit pane for success result

JUnit code for this scenario is,

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class JavaScriptExecutorTest {
	// Declaring variables
	private WebDriver driver;
	private String baseUrl;

	public void setUp() throws Exception {
		// Selenium version 3 beta releases require system property set up
		System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
			+ "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
		// Create a new instance for the class FirefoxDriver
		// that implements WebDriver interface
		driver = new FirefoxDriver();53
		// Implicit wait for 5 seconds
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		// Assign the URL to be invoked to a String variable
		baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";

	public void testPageTitle() throws Exception {
		// Open baseUrl in Firefox browser window
		// Typecast driver to JavascriptExecutor
		JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
		// Execute JavaScript code and assign it to a String
		String pageURL = (String)jsExecutor.executeScript("return document.URL;");
		// Print the URL to the console
		System.out.println("URL : " + pageURL);
		// Print the URL without JavaScript to the console
		System.out.println("URL without JavascriptExecutor: " + driver.getCurrentUrl());
		// Scroll down by 100 pixels
		// Refresh the page
		// Navigating to a different page
		jsExecutor.executeScript("window.location = 'https://www.google.com/';");
	} // End of @Test

	public void tearDown() throws Exception {
		// Close the Firefox browser

Execution Result:

Comments are provided for each line of code making it self-explanatory.

In JUnit pane, the green bar shows that the test case is executed successfully. Console window shows the absence of any errors. It also shows all the printed messages as expected.

Eclipse IDE console output

Time to experiment today’s skills. And yes, put on your safety helmets so that you don’t bump into any exceptions!

All the code files are placed in the GitHub repo for easy access. You can star and fork the repository for convenience. Please go through the ‘README.md’ file for clear instructions.

Have a great day!


Lakshmi Chandana is a Software professional + passion-fueled blogger + novel-reader + artist + tutor to make your day a little brighter than it was before! She is thrilled you are here! She is on a mission to make sure learning sticks but with the fun part kept intact. She uses certain tricks called BrainBells (inspired from barbells and dumbbells used for workout) to achieve this and she says, “this is not the hardest job! As once minions said, it for sure is working in a bubble wrap factory. Imagine the self-control needed!” So, dive in to explore the fun-filled World of Learning!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top Search