[英]Why do we need to typecast Firefox driver to javascript executor?
I'm a beginner in Java and Selenium and I came across JavascriptExecutor
while working. 我是Java和Selenium的初学者,我在工作时遇到了JavascriptExecutor
。
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? 想知道:虽然远程webdriver和Firefox驱动程序实现了javascript执行程序,但为什么我不能直接访问executeScript()
方法,为什么要进行类型转换才能获得访问权限?
Here is the program for javascript executor: 这是javascript执行程序的程序:
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
. 您的driver
变量(实际上是字段)声明为WebDriver
类型。
Since FirefoxDriver
implements WebDriver
, you can assign a new FirefoxDriver()
to driver
without problems. 由于FirefoxDriver
实现了WebDriver
,您可以new FirefoxDriver()
为driver
分配new FirefoxDriver()
。
Now you want to execute some JavaScript command. 现在您要执行一些JavaScript命令。 To do that, you must use the executeScript()
method of the JavascriptExecutor
interface. 为此,您必须使用JavascriptExecutor
接口的executeScript()
方法。
JavascriptExecutor
has nothing to do with the WebDriver
interface (this one doesn't extend that one, for example), but FirefoxDriver
happens to implement both. JavascriptExecutor
与WebDriver
接口无关(例如,这个不扩展那个接口),但FirefoxDriver
碰巧实现了这两者。
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
). 因此,即使您的driver
变量被视为WebDriver
(由于其声明),它实际上将值保存为FirefoxDriver
的实例 - 因此它的值也是 JavascriptExecutor
(因为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()
). 但是,您必须找到一种“查看”该driver
变量的方法,就像它是一个JavascriptExecutor
,因此您可以执行此接口的方法(如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
. 如果您声明类型为FirefixDriver
driver
,则不必进行任何FirefixDriver
。 Try it yourself. 亲自尝试一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.