Hello folks,
In previous post, we have learnt why do we need javascript in Selenium webdriver. In this post we will learn how to run javascript commands in selenium webdriver.
Selenium people provides an interface named “JavascriptExecutor“, which provides declaration of two methods as below:
- Object executeScript(String arg0, Object… arg1);
- Object executeAsyncScript(String arg0, Object… arg1);
This interface enable a browser to execute javascript command using above methods.
RemoteWebDriver implements JavascriptExecutor and provides definition to both methods. All browser driver classes like ChromeDriver etc extends RemoteWebDriver , which enables to execute Javascript commands in selenium script.
Let’s learn more basics:
I see people who just downcast a driver object to execute javascript command without knowing whether it is required and they get stuck.
You must need to know the hierarchy of classes of interfaces in Selenium webdriver.
At high level, WebDriver is super interface in hierarchy and RemoteWebDriver is fully implemented classes of it. Along with WebDriver , RemoteWebDriver implements JavascriptExecutor interface as well. Now, let’s see different scenarios:
Case 1:
If you create a browser driver class object and up cast it to WebDriver as below:
WebDriver driver= new ChromeDriver();
In this case we need to down cast “driver” to “JavascriptExecutor” to execute javascript commands.
Reason of down casting is that, “WebDriver” interface has no visibility of methods of “JavascriptExecutor” (executeScript and executeAsyncScript). So to execute javascript command in this case, you must need to down cast driver.
Example code:
Output:
You will see “Hello” printed in browser console.
Case 2:
If you create a browser driver class object and do not up cast it as below:
ChromeDriver driver= new ChromeDriver();
In this case, you do not need to downcast it to JavascriptExecutor as driver has visibility of methods of JavascriptExecutor as browser driver class “ChromeDriver” extends “RemoteWebDriver”. It means ChromeDriver has indirect access of JavascriptExecutor methods.
Example code:
Output will be same as Case 1 above.
Case 3:
If you create a browser driver class object and up cast to RemoteWebDriver it as below:
RemoteWebDriver driver= new ChromeDriver();
In this case we do not need to downcast it to JavascriptExecutor and reason is same as Case 2.
Example code:
Hope you must be clear now when up casting is needed.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium
Good explanation, Thanks for sharing your knowledge.
Thanks Manoj.
Well… Never Tired of appreciating your great work!!… Cant thank you Enough… Thanks for another superb post
Thanks Avinash.