简体   繁体   中英

JavaScriptExecutor js = new ChromeWebDriver(); does not work in Selenium

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM