Home > database >  Why do we need to typecast the WebDriver instance to JavascriptExecutor before calling the executeSc
Why do we need to typecast the WebDriver instance to JavascriptExecutor before calling the executeSc

Time:05-16

JavascriptExecutor is an interface which provides some default code for executeScript method.

RemoteWebDriver implements this interface and overrides the method like this:

@Override
    public Object executeScript(String script, Object... args) {...}

When we create an instance of WebDriver we use an instance like FireFoxDriver or ChromeDriver. These methods will inherit the parent method executeScript.

Yet, whenever we want to call executeScript we never call this method directly from the driver object like this:

driver.executeScript(...)

Instead, we always typecast it to the interface first and then call it.

Here's a sample code:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor executor =(JavascriptExecutor)driver;
executor.executeScript("window.location.href = 'https://google.com';");  

Why do we need to typecast driver to JavascriptExecutor? Why can't we just call driver.executeScript instead? Alternatively, could we typecast it into RemoteWebDriver instead?

CodePudding user response:

We are typecasting because your code is usually using the webdriver type, which is an interface and does not include the executeScript method.

When you pass the driver around as "webdriver" type, the classes assume it only has the WebDriver interface's methods. You could also cast it to Chromedriver type, but that same code would not work for Geckodriver, or other types.

Creditsto pcalkins for this answer.

Hence, you cast it to an interface JavascriptExecutor in order to keep the code generic so that it will work with Geckodriver / Chromedriver etc. Alternatively, you could also cast it to RemoteWebDriver and it would still work. But it's more readable when casted to JavascriptExecutor.

Here's an architecture diagram that explains this perfectly. Credits to qacult.com for this image.

hierarchy of Selenium classes

  • Related