I'm a beginner in Java and Selenium and I came across JavascriptExecutor
while working.
Wanted to know: though Remote webdriver and Firefox driver implement javascript executor, why can't I acess the method executeScript()
directly and why should it be typecasted to get acessed?
Here is the program for javascript executor:
public class entertextwithoutsendkeys
{
WebDriver driver;
public entertextwithoutsendkeys()
{
driver = new FirefoxDriver();
}
@Test
public void entertextpgm()
{
driver.get("https://www.gmail.com/");
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("document.getElementById('Email').value='sh'");
}
}
Your driver
variable (field, actually) is declared as of type WebDriver
.
Since FirefoxDriver
implements WebDriver
, you can assign a new FirefoxDriver()
to driver
without problems.
Now you want to execute some JavaScript command. To do that, you must use the executeScript()
method of the JavascriptExecutor
interface.
JavascriptExecutor
has nothing to do with the WebDriver
interface (this one doesn't extend that one, for example), but FirefoxDriver
happens to implement both.
So, even though your driver
variable is seen as a WebDriver
(due to its declaration), it actually holds as value an instance of FirefoxDriver
- thus its value is a JavascriptExecutor
as well (because FirefoxDriver implements JavascriptExecutor
).
Still, you have to find a way of "looking at" that driver
variable as if it were a JavascriptExecutor
, so you can execute this interface's methods (like executeScript()
). The way to do this , this "looking at", is casting , just as you did.
You wouldn't have to do any cast if you declared driver
as of type FirefixDriver
. Try it yourself.
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.