Event Firing
Event Firing WebDriver” – It hears whatever you do!
WebDriver is an interface to begin with….
All browser implementations, implement this interface and provide concrete implementations for the specific browser and that is how you have InternetExplorerDriver, FirefoxDriver, ChromeDriver etc.,
EventFiringWebDriver is also a concrete implementation of the WebDriver, but what it does is, it doesn’t implement the WebDriver directly, but binds itself to an existing object of any of the webdrivers listed above, and then when used, it triggers events.
So using EventFiringWebDriver you can listen to events such as before text is changed, after text is changed, before url is loaded etc., and choose to do something with the EventFiringWebDriver.
Webdriver has a WebDriverEventListener interface which you can implement and override the particular listener you want. We use this Listener Interface to capture the events generated by EventFiringWebDriver.
Methods available in webdrivereventlistener:
- afterChangeValueOf(WebElement element, WebDriver driver)
- Called after WebElement.clear(), WebElement.sendKeys(…)}.
- afterClickOn(WebElement element, WebDriver driver)
- Called after WebElement.click().
- afterFindBy(By by, WebElement element, WebDriver driver)
- Called after WebDriver.findElement(…), or WebDriver.findElements(…), or WebElement.findElement(…), or WebElement.findElements(…).
- afterNavigateBack(WebDriver driver)
- Called after navigate().back().
- afterNavigateForward(WebDriver driver)
- Called after navigate().forward().
- afterNavigateTo(java.lang.String url, WebDriver driver)
- Called after get(String url) respectively navigate().to(String url).
- afterScript(java.lang.String script, WebDriver driver)
- Called after RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[]).
- beforeChangeValueOf(WebElement element, WebDriver driver)
- Called before WebElement.clear(), WebElement.sendKeys(…).
- beforeClickOn(WebElement element, WebDriver driver)
- Called before WebElement.click().
- beforeFindBy(By by, WebElement element, WebDriver driver)
- Called before WebDriver.findElement(…), or WebDriver.findElements(…), or WebElement.findElement(…), or WebElement.findElements(…).
- beforeNavigateBack(WebDriver driver)
- Called before navigate().back().
- beforeNavigateForward(WebDriver driver)
- Called before navigate().forward().
- beforeNavigateTo(java.lang.String url, WebDriver driver)
- Called before get(String url) respectively navigate().to(String url).
- beforeScript(java.lang.String script, WebDriver driver)
- Called before RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[])
- onException(java.lang.Throwable throwable, WebDriver driver)
- Called whenever an exception would be thrown.
Let us see how to implement this interface to capture our events. The following code snippet gives better idea of implementing it.
Below is the test code:
public class eventlistenerTest {@Testpublic void WedrivereventlistenerTest(){FirefoxDriver d1 = new FirefoxDriver();EventFiringWebDriver event = new EventFiringWebDriver(d1);WebDriverListerners eventListener = new WebDriverListerners();event.register(eventListener);event.manage().window().maximize();event.navigate().to(“https://www.esurance.com/”);event.findElement(By.id(“V1AtxtZipCode”)).sendKeys(“90001″);event.findElement(By.id(“V1AbtnGoZip”)).click();event.findElement(By.id(“IBWC1Clickable_1″)).click();event.findElement(By.id(“ODI1LastNameData”)).sendKeys(“gs”);event.findElement(By.id(“ODI1StreetAddressData_1″)).sendKeys(“sdfgsdf”);event.findElement(By.id(“IBWC2ValidateClickable”)).click();event.quit();}}Now we will implement the WebdriverEventListener Interface by overriding the existing methods.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.bcel.generic.LSTORE;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;
import org.openqa.selenium.support.ui.Select;
import org.testng.Reporter;
public class WebDriverListerners extends AbstractWebDriverEventListener {
private By lastFindBy;
private WebElement lastElement;
private String originalValue;
/*
* URL NAVIGATION | NAVIGATE() & GET()
*/
// Prints the URL before Navigating to specific URL “get(“http://www.esurance.com”);”
@Override
public void beforeNavigateTo(String url, WebDriver driver) {
commonReport(“Before Navigating To : ” + url + “, my url was: “+ driver.getCurrentUrl(),dateTimeStamp());
}
// Prints the current URL after Navigating to specific URL “get(“http://www.esurance.com”);”
@Override
public void afterNavigateTo(String url, WebDriver driver) {
commonReport(“After Navigating To: ” + url + “, my url is: “+ driver.getCurrentUrl(),dateTimeStamp());
}
// Prints the URL before Navigating back “navigate().back()”
@Override
public void beforeNavigateBack(WebDriver driver) {
commonReport(“Before Navigating Back. I was at ” + driver.getCurrentUrl(),dateTimeStamp());
}
// Prints the current URL after Navigating back “navigate().back()”
@Override
public void afterNavigateBack(WebDriver driver) {
commonReport(“After Navigating Back. I’m at ” + driver.getCurrentUrl(),dateTimeStamp());
}
// Prints the URL before Navigating forward “navigate().forward()”
@Override
public void beforeNavigateForward(WebDriver driver) {
commonReport(“Before Navigating Forward. I was at ” + driver.getCurrentUrl(),dateTimeStamp());
}
// Prints the current URL after Navigating forward “navigate().forward()”
@Override
public void afterNavigateForward(WebDriver driver) {
commonReport(“After Navigating Forward. I’m at ” + driver.getCurrentUrl(),dateTimeStamp());
}
/*
* ON EXCEPTION | SCREENSHOT, THROWING ERROR
*/
// Takes screenshot on any Exception thrown during test execution
@Override
public void onException(Throwable throwable, WebDriver webdriver) {
commonReport(“Exception Occured while performing operation on the above element.”,dateTimeStamp());
//You can write your own method to capture the screenshot upon failing
}
/*
* FINDING ELEMENTS | FINDELEMENT() & FINDELEMENTS()
*/
// Called before finding Element(s)
@Override
public void beforeFindBy(By by, WebElement element, WebDriver driver) {
lastFindBy = by;
commonReport(“Trying to find: ‘” + lastFindBy + “‘.”,dateTimeStamp());
}
// Called after finding Element(s)
@Override
public void afterFindBy(By by, WebElement element, WebDriver driver) {
lastFindBy = by;
commonReport(“Found: ‘” + lastFindBy + “‘.”,dateTimeStamp());
}
/*
* CLICK | CLICK()
*/
// Called before clicking an Element
@Override
public void beforeClickOn(WebElement element, WebDriver driver) {
String strlastElement=(element.toString().split(“->”)[1]);
strlastElement=strlastElement.substring(0,strlastElement.length()-1);
commonReport(“Trying to click: ‘” + strlastElement + “‘”,dateTimeStamp());
// Highlight Elements before clicking
for (int i = 0; i < 1; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
“arguments[0].setAttribute(‘style’, arguments[1]);”,
element, “color: yellow; border: 3px solid black;”);
}
}
// Called after clicking an Element
@Override
public void afterClickOn(WebElement element, WebDriver driver) {
String strlastElement=(element.toString().split(“->”)[1]);
strlastElement=strlastElement.substring(0,strlastElement.length()-1);
commonReport(“Clicked Element with: ‘” + strlastElement + “‘”,dateTimeStamp());
}
/*
* CHANGING VALUES | CLEAR() & SENDKEYS()
*/
// Before Changing values
@Override
public void beforeChangeValueOf(WebElement element, WebDriver driver) {
lastElement = element;
if(element.getAttribute(“type”).equals(“text”)||element.getAttribute(“type”).equals(“text”)){
originalValue = element.getText();
// What if the element is not visible anymore?
if (originalValue.isEmpty()) {
originalValue = element.getAttribute(“value”);
}
}
else{
Select slct=new Select(element);
originalValue=slct.getFirstSelectedOption().toString();
}
}
// After Changing values
@Override
public void afterChangeValueOf(WebElement element, WebDriver driver) {
lastElement = element;
String strlastElement=(element.toString().split(“->”)[1]);
strlastElement=strlastElement.substring(0,strlastElement.length()-1);
String changedValue = “”;
if(element.getAttribute(“type”).equals(“text”)||element.getAttribute(“type”).equals(“text”)){
try {
changedValue = element.getText();
} catch (StaleElementReferenceException e) {
onException(e, driver);
return;
}
// What if the element is not visible anymore?
if (changedValue.isEmpty()) {
changedValue = element.getAttribute(“value”);
}
}
else{
Select slct=new Select(element);
changedValue=slct.getFirstSelectedOption().toString();
}
commonReport(“Changing value in element found ‘” + strlastElement
+ “‘ from ‘” + originalValue + “‘ to ‘” + changedValue + “‘”,dateTimeStamp());
}
/*
* SCRIPT – this section will be modified ASAP
*/
// Called before RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[])
@Override
public void beforeScript(String script, WebDriver driver) {
//do nothing
}
// Called before RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[])
@Override
public void afterScript(String script, WebDriver driver) {
//do nothing
}
public void commonReport(String strText,String strTimeStamp){
System.out.println(strTimeStamp+”: “+strText);
}
public String dateTimeStamp(){
String dateTime = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).format(Calendar.getInstance().getTime());
return dateTime;
}
}
This will generate the event description in eclipse console. We can customize this, to generate the events in ReportNG and report to your choice.
JavaScript event firing uses the FireEvent method as –
ISelenium.FireEvent Method
Explicitly simulate an event, to trigger the corresponding “onevent” handler.
void FireEvent(
string locator,
string eventName
);
Parameters
locator
an element locator
eventName
the event name, e.g. “focus” or “blur”
The Selenium API command fireEvent example lets you trigger the event for a particular element on a page so fired the ‘blur’ event for the component
selSession.fireEvent(“edit_field_1”, “blur”);