Event Listeners:
Used when I want on Execution of a particular action/event a
code should be executed. For E.g. , Say on Click of a click a piece of code
should be executed.
This is included in Interface WebDriverEventListener which has the method bodies
which can be used for such purpose. The class which implements this is AbstractWebDriverEventListener
Let us see the implementation of Listeners:
Step 1: Create a Class containing the methods to be used ,
say weblisteners where we can define the methods. Code is as below:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import
org.openqa.selenium.support.events.AbstractWebDriverEventListener;
public class weblisteners extends
AbstractWebDriverEventListener {
public void
afterClickOn(WebElement element, WebDriver driver){
System.out.println("Object
Has been Clicked");
}
}
Step 2: Using the Objects in our main code:
public static void
eventListenersExample(){
WebDriver
webdriver = new FirefoxDriver(); // Create a firefox driver
EventFiringWebDriver
driver = new EventFiringWebDriver(webdriver); // Create a EventFiring driver
weblisteners
listener = new weblisteners(); // Creating object of weblisteners clas as created
above
driver.register(listener);
//
Registering the listener
driver.navigate().to("http://www.google.com.au");
driver.findElement(By.xpath("//*[@id='gb_70']")).click(); // Only here the
EventListeners will be triggered
}
Now, when you execute the eventListenersExample code, on each click, the weblisteners class will be invoked and an appropriate action will be taken.
Extending the example:
Let us suppose we want to run a specific code when a user navigates back, then we need to update define the method appropriately in weblisteners class and that’s it.
public class weblisteners extends
AbstractWebDriverEventListener {
public void
afterClickOn(WebElement element, WebDriver driver){
System.out.println("Object
Has been Clicked");
}
System.out.println("User
has moved back");
}
}
The main code is as below:
public static void
eventListenersExample(){
WebDriver
webdriver = new FirefoxDriver(); // Create a firefox driver
EventFiringWebDriver
driver = new EventFiringWebDriver(webdriver); // Create a EventFiring driver
weblisteners
listener = new weblisteners(); // Creating object of weblisteners clas as created
above
driver.register(listener);
//
Registering the listener
driver.navigate().to("http://www.google.com.au");
driver.findElement(By.xpath("//*[@id='gb_70']")).click(); // Only here the
EventListeners will be triggered
driver.navigate().back(); // here the afterNavigateBack
method will be invoked.
}
No comments:
Post a Comment