How to use Interface WebDriverListener class of org.openqa.selenium.support.events package

Best Selenium code snippet using org.openqa.selenium.support.events.Interface WebDriverListener

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package com.codeborne.selenide.impl;
2
3import com.codeborne.selenide.DownloadsFolder;
4import com.codeborne.selenide.proxy.SelenideProxyServer;
5import org.openqa.selenium.Proxy;
6import org.openqa.selenium.WebDriver;
7import org.openqa.selenium.support.events.WebDriverEventListener;
8import org.openqa.selenium.support.events.WebDriverListener;
9
10import javax.annotation.CheckReturnValue;
11import javax.annotation.Nonnull;
12import javax.annotation.Nullable;
13import javax.annotation.ParametersAreNonnullByDefault;
14
15@ParametersAreNonnullByDefault
16public interface WebDriverContainer {
17  void addListener(WebDriverEventListener listener);
18  void addListener(WebDriverListener listener);
19  void removeListener(WebDriverEventListener listener);
20  void removeListener(WebDriverListener listener);
21  void setWebDriver(WebDriver webDriver);
22  void setWebDriver(WebDriver webDriver, @Nullable SelenideProxyServer selenideProxy);
23  void setWebDriver(WebDriver webDriver, @Nullable SelenideProxyServer selenideProxy, DownloadsFolder browserDownloadsFolder);
24  void resetWebDriver();
25
26  @CheckReturnValue
27  @Nonnull
28  WebDriver getWebDriver();
29
30  @CheckReturnValue
31  @Nullable
32  SelenideProxyServer getProxyServer();
33
34  void setProxy(@Nullable Proxy webProxy);
35
36  @CheckReturnValue
37  @Nonnull
38  WebDriver getAndCheckWebDriver();
39
40  @CheckReturnValue
41  @Nonnull
42  DownloadsFolder getBrowserDownloadsFolder();
43
44  void closeWindow();
45  void closeWebDriver();
46  boolean hasWebDriverStarted();
47
48  void clearBrowserCache();
49
50  @CheckReturnValue
51  @Nonnull
52  String getPageSource();
53
54  @CheckReturnValue
55  @Nonnull
56  String getCurrentUrl();
57
58  @CheckReturnValue
59  @Nonnull
60  String getCurrentFrameUrl();
61}
62
Full Screen
copy
1package uk.co.evoco.webdriver.configuration.driver;
2
3import org.apache.commons.io.FileUtils;
4import org.openqa.selenium.WebDriver;
5import org.openqa.selenium.WebDriverException;
6import org.openqa.selenium.support.events.EventFiringWebDriver;
7import uk.co.evoco.webdriver.WebDriverListener;
8import uk.co.evoco.webdriver.configuration.TestConfigHelper;
9
10import java.io.File;
11import java.io.IOException;
12
13public interface ConfiguredDriver {
14
15     WebDriver getLocalDriver() throws IOException;
16     WebDriver getRemoteDriver() throws IOException;
17     <T> T getOptions() throws IOException;
18
19    /**
20     *ß
21     * @param screenshotPath path to store screenshots
22     * @return configured EventFiringWebDriver
23     * @throws IOException if log directory doesn't exist
24     */
25    default EventFiringWebDriver getDriver(File screenshotPath) throws IOException {
26        WebDriver webDriver;
27        switch (TestConfigHelper.get().getRunType()) {
28            case LOCAL:
29                webDriver = getLocalDriver();
30                break;
31            case GRID:
32            case SAUCELABS:
33                webDriver = getRemoteDriver();
34                break;
35            default:
36                throw new WebDriverException("Must set runType to either LOCAL or GRID in configuration file");
37        }
38        return configureEventFiringWebDriver(webDriver, screenshotPath);
39    }
40
41    /**
42     *
43     * @param webDriver active WebDriver instance
44     * @param screenshotDirectory path to store screenshots
45     * @return configured options object for target browser driver
46     */
47    default EventFiringWebDriver configureEventFiringWebDriver(
48            WebDriver webDriver, File screenshotDirectory) {
49        EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(webDriver);
50        WebDriverListener eventListener = new WebDriverListener();
51        eventListener.setScreenshotDirectory(screenshotDirectory);
52        eventFiringWebDriver.register(eventListener);
53
54        return eventFiringWebDriver;
55    }
56
57    /**
58     * @throws IOException if the log directory cannot be created
59     */
60    default void createLogDirectory() throws IOException {
61        FileUtils.forceMkdir(new File("./logs"));
62    }
63
64    /**
65     *
66     * @param path runtime browser files download directory path
67     * @return Absolute file download path
68     * @throws IOException if the required directory cannot be created
69     */
70    default String createFileDownloadDirectory(String path) throws IOException {
71        String canonicalPath = new File(path).getCanonicalPath();
72        FileUtils.forceMkdir(new File(canonicalPath));
73        return canonicalPath;
74    }
75
76}
77
Full Screen
copy
1package framework.utility;
2
3import org.openqa.selenium.By;
4import org.openqa.selenium.WebDriver;
5import org.openqa.selenium.WebElement;
6import org.openqa.selenium.support.events.WebDriverEventListener;
7import org.slf4j.Logger;
8
9/**
10 * The listener interface for receiving webDriver events.
11 * The class that is interested in processing a webDriver
12 * event implements this interface, and the object created
13 * with that class is registered with a component using the
14 * component's <code>addWebDriverListener<code> method. When
15 * the webDriver event occurs, that object's appropriate
16 * method is invoked.
17 *
18 * @see WebDriverEvent
19 */
20public class WebDriverListener implements WebDriverEventListener {
21	
22	private static final Logger LOG = LogFactory.getLogger(WebDriverListener.class);
23	
24	@Override
25	public void beforeNavigateRefresh(WebDriver driver) {
26		// TODO Auto-generated method stub
27		
28	}
29
30	@Override
31	public void afterNavigateRefresh(WebDriver driver) {
32		// TODO Auto-generated method stub
33		
34	}
35
36	@Override
37	public void beforeChangeValueOf(WebElement element, WebDriver driver,
38			CharSequence[] keysToSend) {
39		// TODO Auto-generated method stub
40		
41	}
42	
43	@Override
44	public void afterChangeValueOf(WebElement element, WebDriver driver,
45			CharSequence[] keysToSend) {
46		LOG.info("Element " + element + " value was changed");
47	}
48	
49	@Override
50	public void beforeClickOn(WebElement element, WebDriver driver) {
51
52	}
53
54	@Override
55	public void afterClickOn(WebElement element, WebDriver driver) {
56		LOG.info("Element " + getElementXpath(element) + " was clicked");
57	}
58
59	@Override
60	public void beforeNavigateTo(String url, WebDriver driver) {
61
62	}
63
64	@Override
65	public void afterNavigateTo(String url, WebDriver driver) {
66		LOG.info("Was navigated to url: " + url);
67	}
68
69	@Override
70	public void beforeNavigateBack(WebDriver driver) {
71
72	}
73
74	@Override
75	public void afterNavigateBack(WebDriver driver) {
76
77	}
78
79	@Override
80	public void beforeNavigateForward(WebDriver driver) {
81
82	}
83
84	@Override
85	public void afterNavigateForward(WebDriver driver) {
86
87	}
88
89	@Override
90	public void beforeFindBy(By by, WebElement element, WebDriver driver) {
91
92	}
93
94	@Override
95	public void afterFindBy(By by, WebElement element, WebDriver driver) {
96
97	}
98
99	@Override
100	public void beforeScript(String script, WebDriver driver) {
101
102	}
103
104	@Override
105	public void afterScript(String script, WebDriver driver) {
106		LOG.info(script + " script was executed");
107	}
108
109	@Override
110	public void onException(Throwable throwable, WebDriver driver) {
111		LOG.info("WebDriver Exception thrown:", throwable.getMessage());
112	}
113	
114	private String getElementXpath(WebElement element) {
115		String elementStringRepresentation = element.toString();
116		if (elementStringRepresentation.contains("xpath:")) {
117			String substringElementStringRepresentation = 
118					elementStringRepresentation.substring(
119							elementStringRepresentation.indexOf("xpath: "), 
120							elementStringRepresentation.length());
121			if (substringElementStringRepresentation.contains("-> xpath:")) {
122				return substringElementStringRepresentation.replaceAll(" -> xpath: ", "/");
123			} else return substringElementStringRepresentation;
124		}
125		return "";
126	}
127
128	@Override
129	public void beforeAlertAccept(WebDriver driver) {
130		// TODO Auto-generated method stub
131		
132	}
133
134	@Override
135	public void afterAlertAccept(WebDriver driver) {
136		// TODO Auto-generated method stub
137		
138	}
139
140	@Override
141	public void afterAlertDismiss(WebDriver driver) {
142		// TODO Auto-generated method stub
143		
144	}
145
146	@Override
147	public void beforeAlertDismiss(WebDriver driver) {
148		// TODO Auto-generated method stub
149		
150	}
151
152	@Override
153	public void beforeSwitchToWindow(String windowName, WebDriver driver) {
154		// TODO Auto-generated method stub
155		
156	}
157
158	@Override
159	public void afterSwitchToWindow(String windowName, WebDriver driver) {
160		// TODO Auto-generated method stub
161		
162	}
163}
164
Full Screen
copy
1import java.io.File;
2import java.io.IOException;
3import java.util.TimerTask;
4import java.util.Date;
5
6import org.apache.commons.io.FileUtils;
7import org.openqa.selenium.OutputType;
8import org.openqa.selenium.TakesScreenshot;
9// Create a class extends with TimerTask
10public class TakeScreenShot extends TimerTask {
11
12    public static String screenTitle;
13
14    public TakeScreenShot(String screenTitle){//constructor to initialize screenTitle
15        this.screenTitle=screenTitle;
16    }
17
18    // Add your task here
19    public void run() {
20        if(screenTitle.equals(driver.getTitle().trim())){
21            //do nothing; // as long as we are on same page dont take screenshot again.
22        }else{
23            screenTitle=driver.getTitle().trim();//if page changes then, take screenshot
24            File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
25            try {
26                FileUtils.copyFile(scrFile, new File("C:\\"+screenTitle+".png"));
27            } catch (IOException e) {
28                e.printStackTrace();
29            }
30        }
31
32    }
33}
34
Full Screen
copy
1WebDriver driver = new FirefoxDriver();
2//create an object of EventFiringWebDriver and pass the driver instance
3EventFiringWebDriver wd = new EventFiringWebDriver(driver);
4//create an object of  class WebDriverListener and pass the driver instance
5WebDriverListener eventListener = new WebDriverListener(driver);
6wd.register(eventListener);
7
Full Screen
copy
1   String title=""; //initially keep title empty
2    //will automatically be called after click on an element
3    public void afterClickOn(WebElement element, WebDriver driver) {
4
5            //title is not equal to previous page title
6
7            if(driver.getTitle()!=title){
8
9            //take screenshot
10
11            //assign the current title to string title
12            title=driver.getTitle();
13
14            }
15
16        }
17
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in Interface-WebDriverListener

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)