Why is type casting done in (JavascriptExecutor) driver?

Chetan ShindeChetan Shinde
1 min read

When working with Selenium, you might’ve seen this line of code:
JavascriptExecutor js = (JavascriptExecutor) driver;

But why do we need this type casting? Let’s break it down simply.

What is JavascriptExecutor?
JavascriptExecutor is an interface in Selenium that allows you to run JavaScript code in the context of the currently loaded web page. It provides powerful methods like executeScript() and executeAsyncScript().

Why Type Casting?
Here you are typecasting the WebDriver object into a JavascriptExecutor so you can access methods like executeScript() and executeAsyncScript().

The WebDriver interface does not expose the executeScript() method. But the actual object (ChromeDriver) implements both WebDriver and JavascriptExecutor.

So to access JavascriptExecutor methods, we type cast:
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
Now, you can use:
js.executeScript("alert('Hello from JS!');");

What is Type Casting in Java?
Type casting means converting one data type into another.
Upcasting (Implicit): WebDriver driver = new ChromeDriver();
Downcasting (Explicit): JavascriptExecutor js = (JavascriptExecutor) driver;
This is safe because chromedriver implements both interfaces.

Final thoughts:
JavascriptExecutor lets you execute JS code in Selenium.
You type cast driver to JavascriptExecutor to access methods like executeScript().
This is a common and necessary practice in Selenium when using JavaScript for advanced DOM interaction.

0
Subscribe to my newsletter

Read articles from Chetan Shinde directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chetan Shinde
Chetan Shinde

SDET | Writing about test automation, Java, Selenium, and everything in between. Helping devs build better software through clean, reliable testing.