Select Page
Selenium

How to use Selenium WebDriver Event Listener?

Selenium has an interface called the ‘WebDriverEventListener’, which has 27 methods. All these methods are event listeners for Selenium WebDriver’s important actions.

How to use Selenium WebDriver Event Listener

In every interview, there is that one common question that an automation tester would face, and that question is, ‘What is the use of Selenium WebDriver Event Listener?’. So in this blog article, we are going to precisely answer that question for you. In addition to that, once you have read this article, you will be in a position to use Selenium WebDriver Event Listener effectively to its full potential.

Selenium WebDriver is a Web Browser automation framework, and everyone is aware of that. Let’s say you want to capture a screenshot after a test case execution, you can write Selenium’s screen capturing snippet inside the testing framework’s ‘afterEach’ hook method. For example, if you want to capture a screenshot before/after every element click. You would have to write a screen capture snippet right after every click action which is not only a cumbersome task to do, but it is also a waste of valuable time. But you can make this process so much easier than this by making use of Selenium Event Listener. By using Selenium Event Listener, you can write the screenshot snippet inside the ‘beforeClickOn’ or ‘afterClickOn’ method.

Selenium has an interface called the ‘WebDriverEventListener’, which has 27 methods. All these methods are event listeners for Selenium WebDriver’s important actions. Let’s not leave any stone unturned and explore them one by one.

Implement WebDriver Event Listener Methods

First and foremost, you would have to create a class that implements the listener methods. Once that is done, you can create a concrete class for the WebDriverEventListener interface as shown below.

import org.openqa.selenium.support.events.WebDriverEventListener;

public class MyListener implements WebDriverEventListener {
    
}

As soon as you have created the class, your IDE will ask you to implement the listener methods. Once you accept the implementation, your class will have all the 27 methods.

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;

public class MyListener implements WebDriverEventListener {

    @Override
    public void beforeAlertAccept(WebDriver driver) {

    }

    @Override
    public void afterAlertAccept(WebDriver driver) {

    }

    @Override
    public void afterAlertDismiss(WebDriver driver) {

    }

    @Override
    public void beforeAlertDismiss(WebDriver driver) {

    }

    @Override
    public void beforeNavigateTo(String url, WebDriver driver) {

    }

    @Override
    public void afterNavigateTo(String url, WebDriver driver) {

    }

    @Override
    public void beforeNavigateBack(WebDriver driver) {

    }

    @Override
    public void afterNavigateBack(WebDriver driver) {

    }

    @Override
    public void beforeNavigateForward(WebDriver driver) {

    }

    @Override
    public void afterNavigateForward(WebDriver driver) {

    }

    @Override
    public void beforeNavigateRefresh(WebDriver driver) {

    }

    @Override
    public void afterNavigateRefresh(WebDriver driver) {

    }

    @Override
    public void beforeFindBy(By by, WebElement element, WebDriver driver) {

    }

    @Override
    public void afterFindBy(By by, WebElement element, WebDriver driver) {

    }

    @Override
    public void beforeClickOn(WebElement element, WebDriver driver) {

    }

    @Override
    public void afterClickOn(WebElement element, WebDriver driver) {

    }

    @Override
    public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {

    }

    @Override
    public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {

    }

    @Override
    public void beforeScript(String script, WebDriver driver) {

    }

    @Override
    public void afterScript(String script, WebDriver driver) {

    }

    @Override
    public void beforeSwitchToWindow(String windowName, WebDriver driver) {

    }

    @Override
    public void afterSwitchToWindow(String windowName, WebDriver driver) {

    }

    @Override
    public void onException(Throwable throwable, WebDriver driver) {

    }

    @Override
    public <X> void beforeGetScreenshotAs(OutputType<X> target) {

    }

    @Override
    public <X> void afterGetScreenshotAs(OutputType<X> target, X screenshot) {

    }

    @Override
    public void beforeGetText(WebElement element, WebDriver driver) {

    }

    @Override
    public void afterGetText(WebElement element, WebDriver driver, String text) {

    }
}

Attaching EventListener with WebDriver

Now that the event listener class has been created, your next task would be to attach the web driver instance with the event listener, and that can be easily done by following the method shown below.

WebDriver driver = new ChromeDriver();

driver.get(“http”://codoid.com);

EventFiringWebDriver eventHandler = new EventFiringWebDriver(driver);

MyListener listener = new MyListener();

eventHandler.register(listener);

The real value of the WebDriver Event Listener comes from your idea and purpose. If you don’t have a purpose to use it, then implementing Event Listener is simply a waste of time. So, make sure to put in some time and thought before you go straight ahead and start things up. In the upcoming sections, as a test automation company, we have shared how we have effectively used Selenium WebDriver Event Listener for our automation testing projects. Let’s take a look at it beginning from ‘onException’.

onException

When you are in a situation that requires you to run a test suite multiple times, there are chances of getting some failures because of the script or application issues. Selenium has 33 common exceptions. If you manage to capture all these exceptions which are thrown during automated test suite execution, it will be extremely useful for auditing purpose. Let’s say you want to know which Selenium exception was triggered the most often in the past three weeks. When you have the exception history & metrics in hand, you can understand whether the automated test suite is stable enough or if it needs any minor tweaks.

Capturing Selenium Exceptions in the ‘onException’ method is pretty easy. But the question here is, ‘How can you store the exceptions for future reference?’. Well, the solution is easy too, as you can use Sentry to store the exceptions. If you are fairly new to Sentry or unaware of how to configure it in your framework, don’t be worried, we’ve got you covered. All you have to do is follow the steps that are listed below to easily configure Sentry in your test automation framework.

Step 1

Add the Sentry maven dependency in POM.xml

<dependency>
            <groupId>io.sentry</groupId>
            <artifactId>sentry</artifactId>
            <version>4.3.0</version>
</dependency>

Step 2

Sign-up in Sentry and create a project.

Step 3

Once the Sentry project is created, you will get the below code which needs to be integrated with your test suite.

Sentry.init(options -> {
            options.setDsn("https://2323.ingest.sentry.io/2323);
});

Note: Each project has its own DSN. So make sure to copy the above snippet from your project and not from here.

Step 4

Create a constructer in the Listener class and add Sentry config inside the constructer.

public class MyListener implements WebDriverEventListener {

    public MyListener(){
        Sentry.init(options -> {
            options.setDsn("https://2323.ingest.sentry.io/2323);
	});
    }
}

Step 5

Now ingest the exceptions in the Sentry from the ‘onException’ method.

@Override
    public void onException(Throwable throwable, WebDriver driver) {
        Sentry.captureException(throwable);
}

afterFindBy

Nowadays, setting up a test automation framework is fairly simple. If you are using JVM-Cucumber & Selenium WebDriver, then the framework setup is pretty much straightforward in all aspects. You need to write Scenarios in the Gherkin format, implement a step definition for each Gherkin step using Page Object, and finally integrate the other required components.

In order to produce a robust test automation suite, you would need the following:

  • A simple and concrete framework
  • A Stable Environment
  • A Skilled Team
  • A team that follows good Object Locating Techniques

The first three requirements are default elements that every test automation suite must-have. When you have a truly skilled Automation Testing Team, then it is pretty much a given fact that they will follow good object locating techniques. However, you just can’t have the same team members for a longer period. So it is vital to ensure the scripting standards and object locating strategies even with the new team members to maintain the robustness of your test automation suite.

As a QA company, we use peer review and pair scripting sessions to ensure the test automation’s scripting quality and its robustness. However, it is a tedious task to review locators for each object. What we do in the afterFindBy method is, use regular expression and search sub-string logics to verify if the XPaths & CSS Selectors have met the standards that have been set.

beforeClickOn

The ‘beforeClickOn’ method comes in handy when you need to take screenshots of every click action for a workflow. Let’s say someone from your team wants to know what and all buttons/links/objects were clicked in an E2E test. Inside the ‘beforeClickOn’ method, you can access the driver instance and save the screenshot in a PDF file.

When you implement the ‘beforeClickOn’ method, make sure to create a config variable to decide whether you would need a screenshot before every click action or not. Another useful aspect is that, instead of saving the page screenshots before clicking, you can store WebElement screenshots and compare them with the excepted images. When you perform visual testing, you can catch if the CSS Styles are not applied for the Web Elements which is also a major advantage.

Conclusion

We hope you have enjoyed reading this blog article and that it will positively impact your efficiency. Now it is time for you to try and implement Selenium WebDriver Event Listener for any of these ideas in your project and see the results for yourself. If you would like to recommend any other ideas that will help improve the existing methods, please feel free to head over to the comments section share your valuable thoughts. Test Automation Services is one of the core services of Codoid. Our team is always ready to explore new implementations using Selenium & Appium. Subscribe to our blog so that you never miss out on our highly useful automation testing blog articles that will help you be at the top of your game.

Written By

Submit a Comment

Your email address will not be published. Required fields are marked *


In every interview, there is that one common question that an automation tester would face, and that question is, ‘What is the use of Selenium WebDriver Event Listener?’. So in this blog article, we are going to precisely answer that question for you. In addition to that, once you have read this article, you will be in a position to use Selenium WebDriver Event Listener effectively to its full potential.

Selenium WebDriver is a Web Browser automation framework, and everyone is aware of that. Let’s say you want to capture a screenshot after a test case execution, you can write Selenium’s screen capturing snippet inside the testing framework’s ‘afterEach’ hook method. For example, if you want to capture a screenshot before/after every element click. You would have to write a screen capture snippet right after every click action which is not only a cumbersome task to do, but it is also a waste of valuable time. But you can make this process so much easier than this by making use of Selenium Event Listener. By using Selenium Event Listener, you can write the screenshot snippet inside the ‘beforeClickOn’ or ‘afterClickOn’ method.

Selenium has an interface called the ‘WebDriverEventListener’, which has 27 methods. All these methods are event listeners for Selenium WebDriver’s important actions. Let’s not leave any stone unturned and explore them one by one.

Implement WebDriver Event Listener Methods

First and foremost, you would have to create a class that implements the listener methods. Once that is done, you can create a concrete class for the WebDriverEventListener interface as shown below.

import org.openqa.selenium.support.events.WebDriverEventListener;

public class MyListener implements WebDriverEventListener {
    
}

As soon as you have created the class, your IDE will ask you to implement the listener methods. Once you accept the implementation, your class will have all the 27 methods.

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;

public class MyListener implements WebDriverEventListener {

    @Override
    public void beforeAlertAccept(WebDriver driver) {

    }

    @Override
    public void afterAlertAccept(WebDriver driver) {

    }

    @Override
    public void afterAlertDismiss(WebDriver driver) {

    }

    @Override
    public void beforeAlertDismiss(WebDriver driver) {

    }

    @Override
    public void beforeNavigateTo(String url, WebDriver driver) {

    }

    @Override
    public void afterNavigateTo(String url, WebDriver driver) {

    }

    @Override
    public void beforeNavigateBack(WebDriver driver) {

    }

    @Override
    public void afterNavigateBack(WebDriver driver) {

    }

    @Override
    public void beforeNavigateForward(WebDriver driver) {

    }

    @Override
    public void afterNavigateForward(WebDriver driver) {

    }

    @Override
    public void beforeNavigateRefresh(WebDriver driver) {

    }

    @Override
    public void afterNavigateRefresh(WebDriver driver) {

    }

    @Override
    public void beforeFindBy(By by, WebElement element, WebDriver driver) {

    }

    @Override
    public void afterFindBy(By by, WebElement element, WebDriver driver) {

    }

    @Override
    public void beforeClickOn(WebElement element, WebDriver driver) {

    }

    @Override
    public void afterClickOn(WebElement element, WebDriver driver) {

    }

    @Override
    public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {

    }

    @Override
    public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {

    }

    @Override
    public void beforeScript(String script, WebDriver driver) {

    }

    @Override
    public void afterScript(String script, WebDriver driver) {

    }

    @Override
    public void beforeSwitchToWindow(String windowName, WebDriver driver) {

    }

    @Override
    public void afterSwitchToWindow(String windowName, WebDriver driver) {

    }

    @Override
    public void onException(Throwable throwable, WebDriver driver) {

    }

    @Override
    public <X> void beforeGetScreenshotAs(OutputType<X> target) {

    }

    @Override
    public <X> void afterGetScreenshotAs(OutputType<X> target, X screenshot) {

    }

    @Override
    public void beforeGetText(WebElement element, WebDriver driver) {

    }

    @Override
    public void afterGetText(WebElement element, WebDriver driver, String text) {

    }
}

Attaching EventListener with WebDriver

Now that the event listener class has been created, your next task would be to attach the web driver instance with the event listener, and that can be easily done by following the method shown below.

WebDriver driver = new ChromeDriver();

driver.get(“http”://codoid.com);

EventFiringWebDriver eventHandler = new EventFiringWebDriver(driver);

MyListener listener = new MyListener();

eventHandler.register(listener);

The real value of the WebDriver Event Listener comes from your idea and purpose. If you don’t have a purpose to use it, then implementing Event Listener is simply a waste of time. So, make sure to put in some time and thought before you go straight ahead and start things up. In the upcoming sections, as a test automation company, we have shared how we have effectively used Selenium WebDriver Event Listener for our automation testing projects. Let’s take a look at it beginning from ‘onException’.

onException

When you are in a situation that requires you to run a test suite multiple times, there are chances of getting some failures because of the script or application issues. Selenium has 33 common exceptions. If you manage to capture all these exceptions which are thrown during automated test suite execution, it will be extremely useful for auditing purpose. Let’s say you want to know which Selenium exception was triggered the most often in the past three weeks. When you have the exception history & metrics in hand, you can understand whether the automated test suite is stable enough or if it needs any minor tweaks.

Capturing Selenium Exceptions in the ‘onException’ method is pretty easy. But the question here is, ‘How can you store the exceptions for future reference?’. Well, the solution is easy too, as you can use Sentry to store the exceptions. If you are fairly new to Sentry or unaware of how to configure it in your framework, don’t be worried, we’ve got you covered. All you have to do is follow the steps that are listed below to easily configure Sentry in your test automation framework.

Step 1

Add the Sentry maven dependency in POM.xml

<dependency>
            <groupId>io.sentry</groupId>
            <artifactId>sentry</artifactId>
            <version>4.3.0</version>
</dependency>

Step 2

Sign-up in Sentry and create a project.

Step 3

Once the Sentry project is created, you will get the below code which needs to be integrated with your test suite.

Sentry.init(options -> {
            options.setDsn("https://2323.ingest.sentry.io/2323);
});

Note: Each project has its own DSN. So make sure to copy the above snippet from your project and not from here.

Step 4

Create a constructer in the Listener class and add Sentry config inside the constructer.

public class MyListener implements WebDriverEventListener {

    public MyListener(){
        Sentry.init(options -> {
            options.setDsn("https://2323.ingest.sentry.io/2323);
	});
    }
}

Step 5

Now ingest the exceptions in the Sentry from the ‘onException’ method.

@Override
    public void onException(Throwable throwable, WebDriver driver) {
        Sentry.captureException(throwable);
}

afterFindBy

Nowadays, setting up a test automation framework is fairly simple. If you are using JVM-Cucumber & Selenium WebDriver, then the framework setup is pretty much straightforward in all aspects. You need to write Scenarios in the Gherkin format, implement a step definition for each Gherkin step using Page Object, and finally integrate the other required components.

In order to produce a robust test automation suite, you would need the following:

  • A simple and concrete framework
  • A Stable Environment
  • A Skilled Team
  • A team that follows good Object Locating Techniques

The first three requirements are default elements that every test automation suite must-have. When you have a truly skilled Automation Testing Team, then it is pretty much a given fact that they will follow good object locating techniques. However, you just can’t have the same team members for a longer period. So it is vital to ensure the scripting standards and object locating strategies even with the new team members to maintain the robustness of your test automation suite.

As a QA company, we use peer review and pair scripting sessions to ensure the test automation’s scripting quality and its robustness. However, it is a tedious task to review locators for each object. What we do in the afterFindBy method is, use regular expression and search sub-string logics to verify if the XPaths & CSS Selectors have met the standards that have been set.

beforeClickOn

The ‘beforeClickOn’ method comes in handy when you need to take screenshots of every click action for a workflow. Let’s say someone from your team wants to know what and all buttons/links/objects were clicked in an E2E test. Inside the ‘beforeClickOn’ method, you can access the driver instance and save the screenshot in a PDF file.

When you implement the ‘beforeClickOn’ method, make sure to create a config variable to decide whether you would need a screenshot before every click action or not. Another useful aspect is that, instead of saving the page screenshots before clicking, you can store WebElement screenshots and compare them with the excepted images. When you perform visual testing, you can catch if the CSS Styles are not applied for the Web Elements which is also a major advantage.

Conclusion

We hope you have enjoyed reading this blog article and that it will positively impact your efficiency. Now it is time for you to try and implement Selenium WebDriver Event Listener for any of these ideas in your project and see the results for yourself. If you would like to recommend any other ideas that will help improve the existing methods, please feel free to head over to the comments section share your valuable thoughts. Test Automation Services is one of the core services of Codoid. Our team is always ready to explore new implementations using Selenium & Appium. Subscribe to our blog so that you never miss out on our highly useful automation testing blog articles that will help you be at the top of your game.