How to use addListener method of org.openqa.selenium.devtools.DevTools class

Best Selenium code snippet using org.openqa.selenium.devtools.DevTools.addListener

Source:ChromeDevToolsNetworkTest.java Github

copy

Full Screen

...96 public void sendRequestWithUrlFiltersAndExtraHeadersAndVerifyRequests() {97 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));98 devTools.send(setBlockedURLs(ImmutableList.of("*://*/*.css")));99 devTools.send(setExtraHTTPHeaders(ImmutableMap.of("headerName", "headerValue")));100 devTools.addListener(loadingFailed(), loadingFailed -> {101 if (loadingFailed.getResourceType().equals(ResourceType.Stylesheet)) {102 Assert.assertEquals(loadingFailed.getBlockedReason(), BlockedReason.inspector);103 }104 });105 devTools.addListener(requestWillBeSent(), requestWillBeSent -> Assert106 .assertEquals(requestWillBeSent.getRequest().getHeaders().get("headerName"),107 "headerValue"));108 devTools.addListener(dataReceived(),109 dataReceived -> Assert.assertNotNull(dataReceived.getRequestId()));110 chromeDriver.get(appServer.whereIs("js/skins/lightgray/content.min.css"));111 }112 @Test113 public void emulateNetworkConditionOffline() {114 devTools.send(enable(Optional.of(100000000), Optional.empty(), Optional.empty()));115 devTools.send(116 emulateNetworkConditions(true, 100, 1000, 2000, Optional.of(ConnectionType.cellular3g)));117 devTools.addListener(loadingFailed(), loadingFailed -> Assert118 .assertEquals(loadingFailed.getErrorText(), "net::ERR_INTERNET_DISCONNECTED"));119 chromeDriver.get(appServer.whereIs("simpleTest.html"));120 }121 @Test122 public void verifyRequestReceivedFromCacheAndResponseBody() {123 final RequestId[] requestIdFromCache = new RequestId[1];124 devTools.send(enable(Optional.empty(), Optional.of(100000000), Optional.empty()));125 devTools.addListener(requestServedFromCache(), requestId -> {126 Assert.assertNotNull(requestId);127 requestIdFromCache[0] = requestId;128 });129 devTools.addListener(loadingFinished(),130 dataReceived -> Assert.assertNotNull(dataReceived.getRequestId()));131 chromeDriver.get(appServer.whereIsSecure("simpleTest.html"));132 chromeDriver.get(appServer.whereIsSecure("simpleTest.html"));133 ResponseBody responseBody = devTools.send(getResponseBody(requestIdFromCache[0]));134 Assert.assertNotNull(responseBody);135 }136 @Test137 public void verifySearchInResponseBody() {138 final RequestId[] requestIds = new RequestId[1];139 devTools.send(enable(Optional.empty(), Optional.of(100000000), Optional.empty()));140 devTools.addListener(responseReceived(), responseReceived -> {141 Assert.assertNotNull(responseReceived);142 requestIds[0] = responseReceived.getRequestId();143 });144 chromeDriver.get(appServer.whereIs("simpleTest.html"));145 Assert.assertEquals(true, devTools.send(146 searchInResponseBody(requestIds[0], "/", Optional.empty(), Optional.empty())).size()147 > 0);148 }149 @Test150 public void verifyCacheDisabledAndClearCache() {151 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.of(100000000)));152 devTools.addListener(responseReceived(), responseReceived -> Assert153 .assertEquals(false, responseReceived.getResponse().getFromDiskCache()));154 chromeDriver.get(appServer.whereIs("simpleTest.html"));155 devTools.send(setCacheDisabled(true));156 chromeDriver.get(appServer.whereIs("simpleTest.html"));157 devTools.send(clearBrowserCache());158 }159 @Test160 public void verifyCertificatesAndOverrideUserAgent() {161 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));162 devTools.send(setUserAgentOverride("userAgent", Optional.empty(), Optional.empty()));163 devTools.addListener(requestWillBeSent(),164 requestWillBeSent -> Assert.assertEquals("userAgent",165 requestWillBeSent166 .getRequest()167 .getHeaders()168 .get("User-Agent")));169 chromeDriver.get(appServer.whereIsSecure("simpleTest.html"));170 Assert.assertEquals(true, devTools171 .send(getCertificate(appServer.whereIsSecure("simpleTest.html")))172 .size() > 0);173 }174 @Test175 public void verifyResponseReceivedEventAndNetworkDisable() {176 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));177 devTools.addListener(responseReceived(), Assert::assertNotNull);178 chromeDriver.get(appServer.whereIs("simpleTest.html"));179 devTools.send(disable());180 }181 @Test182 public void verifyWebSocketOperations() {183 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));184 devTools.addListener(webSocketCreated(), Assert::assertNotNull);185 devTools.addListener(webSocketFrameReceived(), Assert::assertNotNull);186 devTools.addListener(webSocketClosed(), Assert::assertNotNull);187 devTools.addListener(webSocketFrameError(), Assert::assertNotNull);188 devTools.addListener(webSocketFrameSent(), Assert::assertNotNull);189 chromeDriver.get(appServer.whereIs("simpleTest.html"));190 }191 @Test192 public void verifyRequestPostData() {193 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));194 final RequestId[] requestIds = new RequestId[1];195 devTools.addListener(requestWillBeSent(), requestWillBeSent -> {196 Assert.assertNotNull(requestWillBeSent);197 if (requestWillBeSent.getRequest().getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {198 requestIds[0] = requestWillBeSent.getRequestId();199 }200 });201 chromeDriver.get(appServer.whereIs("postForm.html"));202 chromeDriver.findElement(By.xpath("/html/body/form/input")).click();203 Assert.assertNotNull(devTools.send(getRequestPostData(requestIds[0])));204 }205 @Test206 public void byPassServiceWorker() {207 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));208 devTools.send(setBypassServiceWorker(true));209 System.out.println("");210 }211 @Test212 public void dataSizeLimitsForTest() {213 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));214 devTools.send(setDataSizeLimitsForTest(10000, 100000));215 System.out.println("");216 }217 @Test218 public void verifyEventSourceMessage() {219 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));220 devTools.addListener(eventSourceMessageReceived(), Assert::assertNotNull);221 chromeDriver.get(appServer.whereIs("simpleTest.html"));222 }223 @Test224 public void verifySignedExchangeReceived() {225 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));226 devTools.addListener(signedExchangeReceived(), Assert::assertNotNull);227 chromeDriver.get(appServer.whereIsSecure("simpleTest.html"));228 }229 @Test230 public void verifyResourceChangedPriority() {231 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));232 devTools.addListener(resourceChangedPriority(), Assert::assertNotNull);233 chromeDriver.get(appServer.whereIsSecure("simpleTest.html"));234 }235 @Test236 public void interceptRequestAndContinue() {237 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));238 devTools.addListener(requestIntercepted(),239 requestIntercepted -> devTools.send(240 continueInterceptedRequest(requestIntercepted.getInterceptionId(),241 Optional.empty(),242 Optional.empty(),243 Optional.empty(), Optional.empty(),244 Optional.empty(),245 Optional.empty(), Optional.empty())));246 RequestPattern247 requestPattern =248 new RequestPattern("*.css", ResourceType.Stylesheet, InterceptionStage.HeadersReceived);249 devTools.send(setRequestInterception(ImmutableList.of(requestPattern)));250 chromeDriver.get(appServer.whereIs("js/skins/lightgray/content.min.css"));251 }252}...

Full Screen

Full Screen

Source:ChromeDevToolsTargetTest.java Github

copy

Full Screen

...46public class ChromeDevToolsTargetTest extends DevToolsTestBase {47 private final int id = 123;48 @Test49 public void getTargetActivateAndAttach() {50 devTools.addListener(attachedToTarget(), Assert::assertNotNull);51 driver.get(appServer.whereIs("devToolsConsoleTest.html"));52 List<TargetInfo> allTargets = devTools.send(getTargets());53 for (TargetInfo target : allTargets) {54 validateTarget(target);55 devTools.send(activateTarget(target.getTargetId()));56 SessionID sessionId =57 devTools.send(attachToTarget(target.getTargetId(), Optional.of(Boolean.FALSE)));58 validateSession(sessionId);59 TargetInfo infods = devTools.send(getTargetInfo(Optional.of(target.getTargetId())));60 validateTargetInfo(infods);61 }62 }63 @Test64 public void getTargetAndSendMessageToTarget() {65 List<TargetInfo> allTargets = null;66 SessionID sessionId = null;67 TargetInfo targetInfo = null;68 driver.get(appServer.whereIs("devToolsConsoleTest.html"));69 devTools.addListener(receivedMessageFromTarget(), this::validateMessage);70 allTargets = devTools.send(getTargets());71 validateTargetsInfos(allTargets);72 ArrayList<TargetInfo> listTargets = new ArrayList<>(allTargets);73 validateTarget(listTargets.get(0));74 targetInfo = listTargets.get(0);75 devTools.send(activateTarget(targetInfo.getTargetId()));76 sessionId = devTools.send(attachToTarget(targetInfo.getTargetId(), Optional.of(false)));77 validateSession(sessionId);78 devTools.send(79 sendMessageToTarget(80 "{\"id\":" + id + ",\"method\":\"Page.bringToFront\"}",81 Optional.of(sessionId),82 Optional.of(targetInfo.getTargetId())));83 }84 @Test85 public void createAndContentLifeCycle() {86 devTools.addListener(targetCreated(), this::validateTargetInfo);87 devTools.addListener(targetCrashed(), this::validateTargetCrashed);88 devTools.addListener(targetDestroyed(), this::validateTargetId);89 devTools.addListener(targetInfoChanged(), this::validateTargetInfo);90 TargetID target =91 devTools.send(92 createTarget(93 appServer.whereIs("devToolsConsoleTest.html"),94 Optional.empty(),95 Optional.empty(),96 Optional.empty(),97 Optional.empty(),98 Optional.of(Boolean.TRUE),99 Optional.of(Boolean.FALSE)));100 validateTargetId(target);101 devTools.send(setDiscoverTargets(true));102 Boolean isClosed = devTools.send(closeTarget(target));103 assertNotNull(isClosed);...

Full Screen

Full Screen

Source:Main.java Github

copy

Full Screen

...50 private static void enableNetworkOffline(DevTools devTools) {51 devTools.send(Network.enable(Optional.of(100000000), Optional.empty(), Optional.empty()));52 devTools.send(emulateNetworkConditions(true, 100, 1000, 2000,53 Optional.of(ConnectionType.cellular3g)));54 devTools.addListener(loadingFailed(), loadingFailed -> assertEquals(loadingFailed.getErrorText(), "net::ERR_INTERNET_DISCONNECTED"));55 }56 /**57 * Enable Network Online58 * @param devTools59 */60 private static void enableNetworkOnline(DevTools devTools) {61 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));62 devTools.send(emulateNetworkConditions(false, 100, 5000, 2000,63 Optional.of(ConnectionType.cellular4g)));64 }65 /**66 * Intercept Network67 * @param chromeDevTools68 */69 private static void interceptNetwork(DevTools chromeDevTools) {70 chromeDevTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));71 //set blocked URL patterns72 chromeDevTools.send(Network.setBlockedURLs(ImmutableList.of("*.css", "*.jpg")));73 //add event listener to verify that css and png are blocked74 chromeDevTools.addListener(loadingFailed(), loadingFailed -> {75 if (loadingFailed.getResourceType().equals(ResourceType.Stylesheet)) {76 assertEquals(loadingFailed.getBlockedReason(), BlockedReason.inspector);77 }78 else if (loadingFailed.getResourceType().equals(ResourceType.Image)) {79 assertEquals(loadingFailed.getBlockedReason(), BlockedReason.mixedContent);80 }81 });82 }83 /**84 * Inspect Detached Network85 * @param devTools86 */87 private static void inspectDetached(DevTools devTools) {88 devTools.addListener(detached(), Assert::assertNotNull);89 devTools.send(Inspector.enable());90 Set<TargetInfo> targetInfos = devTools.send(Target.getTargets());91 targetInfos.forEach(92 targetInfo -> {93 var sessionId = devTools.send(attachToTarget(targetInfo.getTargetId(), Optional.of(false)));94 devTools.send(95 Target.sendMessageToTarget(96 "{\"method\":\"Page.crash\"}",97 Optional.of(sessionId),98 Optional.of(targetInfo.getTargetId())));99 });100 devTools.send(Inspector.disable());101 }102 /**103 * Get Console Logs104 * @param chromeDevTools105 * @param message106 */107 private static void consoleLogs(DevTools chromeDevTools, String message) {108 chromeDevTools.send(Console.enable());109 //add listener to verify the console message110 chromeDevTools.addListener(Console.messageAdded(), consoleMessageFromDevTools ->111 assertEquals(true, consoleMessageFromDevTools.getText().equals(message)));112 }113 /**114 * Selenium Misc features115 * @param chromeDriver116 */117 private static void Selenium4MiscFetures(ChromeDriver chromeDriver){118 // New Tab119 var newTab = chromeDriver.switchTo().newWindow(WindowType.TAB);120 newTab.get("http://executeautomation.com/demosite/Login.html");121 //login122 newTab.findElement(By.name("UserName")).sendKeys("admin");123 newTab.findElement(By.name("Password")).sendKeys("admin");124 newTab.findElement(By.name("Login")).submit();...

Full Screen

Full Screen

Source:ChromeDevToolsProfilerTest.java Github

copy

Full Screen

...78 devTools.send(disable());79 }80 @Test81 public void sampleProfileEvents() {82 devTools.addListener(consoleProfileFinished(), Assert::assertNotNull);83 devTools.addListener(consoleProfileStarted(), Assert::assertNotNull);84 devTools.send(enable());85 driver.get(appServer.whereIs("devToolsProfilerTest.html"));86 devTools.addListener(consoleProfileStarted(), Assert::assertNotNull);87 devTools.send(startTypeProfile());88 devTools.send(start());89 driver.navigate().refresh();90 devTools.send(stopTypeProfile());91 Profile profiler = devTools.send(stop());92 validateProfile(profiler);93 devTools.send(disable());94 }95}...

Full Screen

Full Screen

Source:DevToolsApiUtils.java Github

copy

Full Screen

...22 public static void viewConsoleLogs(ChromeDriver driver) {23 DevTools devTools = driver.getDevTools();24 devTools.createSession();25 devTools.send(Log.enable());26 devTools.addListener(Log.entryAdded(),LogEntry ->{27 System.out.println("Logs: "+LogEntry.getText());28 System.out.println("Level: "+LogEntry.getLevel());29 });30 }31 /*32 * To mock geo-location33 */34 public static void viewGeoLocation(ChromeDriver driver) {35 DevTools devTools = driver.getDevTools();36 devTools.createSession();37 devTools.send(Emulation.setGeolocationOverride(Optional.of(25.321684), Optional.of(82.987289), Optional.of(100)));38 }39 /*40 * To simulate Network41 */42 public static void simulateNetwork(ChromeDriver driver) {43 DevTools devTools = driver.getDevTools();44 devTools.createSession();45 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));46 devTools.send(Network.emulateNetworkConditions(47 false,100,200000,100000,Optional.of(ConnectionType.CELLULAR3G))); //"true" to test in offline mode48 }49 /*50 * To handle certificate errors51 */52 public static void handleSSLCertificatesError(ChromeDriver driver) {53 DevTools devTools = driver.getDevTools();54 devTools.createSession();55 devTools.send(Security.enable());56 devTools.send(Security.setIgnoreCertificateErrors(true));57 }58 /*59 * Simulate Devices60 */61 @SuppressWarnings({ "rawtypes", "serial", "unchecked" })62 public static void simulateDevice(ChromeDriver driver) {63 DevTools devTools = driver.getDevTools();64 devTools.createSession();65 Map deviceMetrics = new HashMap()66 {{67 put("width", 600);68 put("height", 1000);69 put("mobile", true);70 put("deviceScaleFactor", 50);71 }};72 driver.executeCdpCommand("Emulation.setDeviceMetricsOverride", deviceMetrics);73 }74 /*75 * Capture HTTP Requests76 */77 public static void captureHttpRequests(ChromeDriver driver) {78 DevTools devTools = driver.getDevTools();79 devTools.createSession();80 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));81 devTools.addListener(Network.requestWillBeSent(),82 entry -> {83 System.out.println("Request URI : " + entry.getRequest().getUrl()+"\n"84 + " With method : "+entry.getRequest().getMethod() + "\n");85 entry.getRequest().getMethod();86 87 });88 }89 90 /*91 * Capture HTTP Requests92 */93 public static void capturePerformance(ChromeDriver driver) {94 DevTools devTools = driver.getDevTools();95 devTools.createSession();96 devTools.send(Performance.enable(Optional.empty()));97 devTools.addListener(Performance.metrics(),98 metric -> {99 System.out.println("Metrics are: "+ metric.getTitle());100 101 });102 Command<List<Metric>> metrics = Performance.getMetrics();103 System.out.println("Performace Response: "+metrics.getSendsResponse());104 105 }106}...

Full Screen

Full Screen

addListener

Using AI Code Generation

copy

Full Screen

1package com.example;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.devtools.DevTools;7import org.openqa.selenium.devtools.v87.log.Log;8import java.util.Optional;9import java.util.function.Consumer;10public class DevToolsExample {11 public static void main(String[] args) {12 WebDriver driver = new ChromeDriver();13 DevTools devTools = ((ChromeDriver) driver).getDevTools();14 devTools.createSession();15 devTools.send(Log.enable(Optional.empty()));16 devTools.addListener(Log.entryAdded(), new Consumer<Log.EntryAdded>() {17 public void accept(Log.EntryAdded entryAdded) {18 System.out.println(entryAdded.getText());19 }20 });21 WebElement element = driver.findElement(By.name("q"));22 element.sendKeys("Selenium");23 element.submit();24 driver.quit();25 }26}

Full Screen

Full Screen

addListener

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.devtools.DevTools;2import org.openqa.selenium.devtools.v87.network.Network;3import org.openqa.selenium.devtools.v87.network.model.Headers;4public class DevToolsTest {5 public static void main(String[] args) {6 DevTools devTools = ((ChromeDriver) driver).getDevTools();7 devTools.createSession();8 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));9 devTools.addListener(Network.requestWillBeSent(), request -> {10 System.out.println("Request URL: " + request.getRequest().getUrl());11 System.out.println("Request Headers: " + request.getRequest().getHeaders());12 });13 }14}15Request Headers: {Accept-Language=[en-US], User-Agent=[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36], Accept=[text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9], Sec-Fetch-Site=[none], Sec-Fetch-Mode=[navigate], Sec-Fetch-User=[?1], Sec-Fetch-Dest=[document], Upgrade-Insecure-Requests=[1]}16devTools.removeListener(event, listener);17import org.openqa.selenium.devtools.DevTools;18import org.openqa.selenium.devtools.v87.network.Network;19import org.openqa.selenium.devtools.v87.network.model.Headers;20public class DevToolsTest {21 public static void main(String[] args) {22 DevTools devTools = ((ChromeDriver) driver).getDevTools();

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful