Reputation: 21
I was trying to understand the Selenium API and came across the fact that RemoteWebDriver class actually implements WebDriver and JAVAScriptExecutor abstract methods and further we have subclasses for specific browser implementation like chromedriver, firefoxdriver etc.
I want to know why this holds
INVALID 'JavaScriptExecutor js = new ChromeDriver();'
but this VALID 'WebDriver driver = new ChromeDriver();' VALID 'JavaScriptExecutor js = (JavaScriptExecutor) driver;' VALID 'JavaScriptExecutor js = (JavaScriptExecutor) new ChromeDriver();'
Please note that the first one gives error "Type mismatch: cannot convert from ChromeDriver to JavaScriptExecutor".
I have tried to looked into the selenium API and upcasting/downcasting concepts but not able to understand why only JavaScriptExecutor needs typecasting here and not WebDriver though both of them get implemented by RemoteWebDriver class.
Upvotes: 0
Views: 813
Reputation: 3690
You are missing the cast:
WebDriver driver = new ChromeDriver(); // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");
ChromeDriver is a child class, it inherits all interfaces that RemoteWebDriver implements. JavascriptExecutor is just one of the interfaces that ChromeDriver (RemoteWebDriver) implement.
Reference:
https://www.selenium.dev/documentation/legacy/selenium_2/faq/#q-how-do-i-execute-javascript-directly
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/chrome/ChromeDriver.html
Upvotes: 1