Best Selenium code snippet using org.openqa.selenium.devtools.DevTools.send
Source:ChromeDevToolsNetworkTest.java
...76import static org.openqa.selenium.testing.drivers.Browser.CHROME;77public class ChromeDevToolsNetworkTest extends DevToolsTestBase {78 @Test79 public void getSetDeleteAndClearAllCookies() {80 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));81 List<Cookie> allCookies = devTools.send(getAllCookies());82 assertEquals(0, allCookies.size());83 boolean setCookie = devTools.send(setCookie(84 "name",85 "value",86 Optional.of("http://localhost/devtools/test"),87 Optional.of("localhost"),88 Optional.of("/devtools/test"),89 Optional.empty(),90 Optional.empty(),91 Optional.empty(),92 Optional.empty(),93 Optional.empty()));94 assertTrue(setCookie);95 assertEquals(1, devTools.send(getAllCookies()).size());96 assertEquals(0, devTools.send(getCookies(Optional.empty())).size());97 devTools.send(deleteCookies("name", Optional.empty(), Optional.of("localhost"),98 Optional.of("/devtools/test")));99 devTools.send(clearBrowserCookies());100 assertEquals(0, devTools.send(getAllCookies()).size());101 setCookie = devTools.send(setCookie(102 "name",103 "value",104 Optional.of("http://localhost/devtools/test"),105 Optional.of("localhost"),106 Optional.of("/devtools/test"),107 Optional.empty(),108 Optional.empty(),109 Optional.empty(),110 Optional.empty(),111 Optional.empty()));112 assertTrue(setCookie);113 assertEquals(1, devTools.send(getAllCookies()).size());114 }115 @Test116 public void sendRequestWithUrlFiltersAndExtraHeadersAndVerifyRequests() {117 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));118 devTools.send(setBlockedURLs(singletonList("*://*/*.css")));119 devTools.send(setExtraHTTPHeaders(new Headers(ImmutableMap.of("headerName", "headerValue"))));120 devTools.addListener(loadingFailed(), loadingFailed -> {121 if (loadingFailed.getType().equals(ResourceType.STYLESHEET)) {122 assertEquals(loadingFailed.getBlockedReason(), BlockedReason.INSPECTOR);123 }124 });125 devTools.addListener(requestWillBeSent(), requestWillBeSent -> assertEquals(requestWillBeSent.getRequest().getHeaders().get("headerName"),126 "headerValue"));127 devTools.addListener(dataReceived(),128 dataReceived -> Assert.assertNotNull(dataReceived.getRequestId()));129 driver.get(appServer.whereIs("js/skins/lightgray/content.min.css"));130 }131 @Test132 public void emulateNetworkConditionOffline() {133 devTools.send(enable(Optional.of(100000000), Optional.empty(), Optional.empty()));134 devTools.send(135 emulateNetworkConditions(true, 100, 1000, 2000, Optional.of(ConnectionType.CELLULAR3G)));136 devTools.addListener(loadingFailed(), loadingFailed -> assertEquals(loadingFailed.getErrorText(), "net::ERR_INTERNET_DISCONNECTED"));137 driver.get(appServer.whereIs("simpleTest.html"));138 }139 @Test140 public void verifyRequestReceivedFromCacheAndResponseBody() {141 final RequestId[] requestIdFromCache = new RequestId[1];142 devTools.send(enable(Optional.empty(), Optional.of(100000000), Optional.empty()));143 devTools.addListener(requestServedFromCache(), requestId -> {144 Assert.assertNotNull(requestId);145 requestIdFromCache[0] = requestId;146 });147 devTools.addListener(loadingFinished(),148 dataReceived -> Assert.assertNotNull(dataReceived.getRequestId()));149 driver.get(appServer.whereIsSecure("simpleTest.html"));150 driver.get(appServer.whereIsSecure("simpleTest.html"));151 Network.GetResponseBodyResponse responseBody = devTools.send(getResponseBody(requestIdFromCache[0]));152 Assert.assertNotNull(responseBody);153 }154 @Test155 public void verifySearchInResponseBody() {156 final RequestId[] requestIds = new RequestId[1];157 devTools.send(enable(Optional.empty(), Optional.of(100000000), Optional.empty()));158 devTools.addListener(responseReceived(), responseReceived -> {159 Assert.assertNotNull(responseReceived);160 Assert.assertNotNull(responseReceived.getResponse().getTiming());161 requestIds[0] = responseReceived.getRequestId();162 });163 driver.get(appServer.whereIs("simpleTest.html"));164 assertTrue(devTools.send(165 searchInResponseBody(requestIds[0], "/", Optional.empty(), Optional.empty())).size()166 > 0);167 }168 @Test169 public void verifyCacheDisabledAndClearCache() {170 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.of(100000000)));171 driver.get(appServer.whereIs("simpleTest.html"));172 devTools.send(setCacheDisabled(true));173 devTools.addListener(responseReceived(), responseReceived -> assertEquals(false, responseReceived.getResponse().getFromDiskCache()));174 driver.get(appServer.whereIs("simpleTest.html"));175 devTools.send(clearBrowserCache());176 }177 @Test178 @NotYetImplemented(CHROME)179 public void verifyCertificatesAndOverrideUserAgent() {180 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));181 devTools.send(setUserAgentOverride("userAgent", Optional.empty(), Optional.empty(), Optional.empty()));182 devTools.addListener(requestWillBeSent(),183 requestWillBeSent -> assertEquals("userAgent",184 requestWillBeSent185 .getRequest()186 .getHeaders()187 .get("User-Agent")));188 driver.get(appServer.whereIsSecure("simpleTest.html"));189 assertThat(devTools.send(getCertificate(appServer.whereIsSecure("simpleTest.html")))).isNotEmpty();190 }191 @Test192 public void verifyResponseReceivedEventAndNetworkDisable() {193 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));194 devTools.addListener(responseReceived(), Assert::assertNotNull);195 driver.get(appServer.whereIs("simpleTest.html"));196 devTools.send(disable());197 }198 @Test199 public void verifyWebSocketOperations() {200 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));201 devTools.addListener(webSocketCreated(), Assert::assertNotNull);202 devTools.addListener(webSocketFrameReceived(), Assert::assertNotNull);203 devTools.addListener(webSocketClosed(), Assert::assertNotNull);204 devTools.addListener(webSocketFrameError(), Assert::assertNotNull);205 devTools.addListener(webSocketFrameSent(), Assert::assertNotNull);206 driver.get(appServer.whereIs("simpleTest.html"));207 }208 @Test209 public void verifyRequestPostData() {210 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));211 final RequestId[] requestIds = new RequestId[1];212 devTools.addListener(requestWillBeSent(), requestWillBeSent -> {213 Assert.assertNotNull(requestWillBeSent);214 if (requestWillBeSent.getRequest().getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {215 requestIds[0] = requestWillBeSent.getRequestId();216 }217 });218 driver.get(appServer.whereIs("postForm.html"));219 driver.findElement(By.xpath("/html/body/form/input")).click();220 Assert.assertNotNull(devTools.send(getRequestPostData(requestIds[0])));221 }222 @Test223 public void byPassServiceWorker() {224 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));225 devTools.send(setBypassServiceWorker(true));226 }227 @Test228 public void dataSizeLimitsForTest() {229 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));230 devTools.send(setDataSizeLimitsForTest(10000, 100000));231 }232 @Test233 public void verifyEventSourceMessage() {234 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));235 devTools.addListener(eventSourceMessageReceived(), Assert::assertNotNull);236 driver.get(appServer.whereIs("simpleTest.html"));237 }238 @Test239 public void verifySignedExchangeReceived() {240 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));241 devTools.addListener(signedExchangeReceived(), Assert::assertNotNull);242 driver.get(appServer.whereIsSecure("simpleTest.html"));243 }244 @Test245 public void verifyResourceChangedPriority() {246 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));247 devTools.addListener(resourceChangedPriority(), Assert::assertNotNull);248 driver.get(appServer.whereIsSecure("simpleTest.html"));249 }250 @Test251 public void interceptRequestAndContinue() {252 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));253 devTools.addListener(requestIntercepted(),254 requestIntercepted -> devTools.send(255 continueInterceptedRequest(requestIntercepted.getInterceptionId(),256 Optional.empty(),257 Optional.empty(),258 Optional.empty(), Optional.empty(),259 Optional.empty(),260 Optional.empty(), Optional.empty())));261 RequestPattern requestPattern = new RequestPattern(262 Optional.of("*.css"),263 Optional.of(ResourceType.STYLESHEET),264 Optional.of(InterceptionStage.HEADERSRECEIVED));265 devTools.send(setRequestInterception(ImmutableList.of(requestPattern)));266 driver.get(appServer.whereIs("js/skins/lightgray/content.min.css"));267 }268}...
Source:ChromeDevToolsTargetTest.java
...36import static org.openqa.selenium.devtools.v84.target.Target.createTarget;37import static org.openqa.selenium.devtools.v84.target.Target.getTargetInfo;38import static org.openqa.selenium.devtools.v84.target.Target.getTargets;39import static org.openqa.selenium.devtools.v84.target.Target.receivedMessageFromTarget;40import static org.openqa.selenium.devtools.v84.target.Target.sendMessageToTarget;41import static org.openqa.selenium.devtools.v84.target.Target.setDiscoverTargets;42import static org.openqa.selenium.devtools.v84.target.Target.targetCrashed;43import static org.openqa.selenium.devtools.v84.target.Target.targetCreated;44import static org.openqa.selenium.devtools.v84.target.Target.targetDestroyed;45import static org.openqa.selenium.devtools.v84.target.Target.targetInfoChanged;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);104 assertTrue(isClosed);105 }106 private void validateTargetCrashed(TargetCrashed targetCrashed) {107 assertNotNull(targetCrashed);108 assertNotNull(targetCrashed.getStatus());109 assertNotNull(targetCrashed.getTargetId());110 }111 private void validateTargetId(TargetID targetId) {112 assertNotNull(targetId);113 }114 private void validateMessage(ReceivedMessageFromTarget messageFromTarget) {115 assertNotNull(messageFromTarget);116 assertNotNull(messageFromTarget.getMessage());...
Source:Main.java
...47 * Enable Network Offline48 * @param devTools49 */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();125 var checkbox = chromeDriver.findElement(withTagName("input").below(By.name("Male")).toLeftOf(By.name("Hindi")));126 checkbox.click();127 System.out.println(checkbox.getAttribute("name"));128 var txtIntial = chromeDriver.findElement(withTagName("input")129 .below(By.id("TitleId"))130 .above(By.id("FirstName")));131 txtIntial.sendKeys("KK");132 //list of elements133 var lstElements = chromeDriver.findElements(withTagName("input")134 .below(By.xpath("//h2[text()=' User Form ']"))135 .above(By.name("Save")));136 var elements = lstElements137 .stream()138 .map(x -> x.getAttribute("input"));139 //should be 7140 System.out.println(elements.count());141 }142}...
Source:Selenium4CDPTest.java
...35 @Test36 public void simulateNetworkBandwidthTest() throws InterruptedException {37 driver.get("http://www.google.com");38 devTools.createSession();39 devTools.send(40 enable(Optional.of(100000000), Optional.empty(), Optional.empty()));41 devTools.send(emulateNetworkConditions(false, 100, 1000, 2000,42 Optional.of(ConnectionType.cellular3g)));43 driver.get("https://seleniumconf.co.uk");44 waitForWebsiteToLoad();45 }46 @Test47 public void simulateBandwidthWithExecCDPTest() throws InterruptedException {48 MessageBuilder message = Messages.enableNetwork();49 driver.get("http://www.google.com");50 driver.executeCdpCommand(message.method, message.params);51 MessageBuilder simulateNetwork = Messages.setNetworkBandWidth();52 driver.executeCdpCommand(simulateNetwork.method, simulateNetwork.params);53 driver.get("https://seleniumconf.co.uk");54 waitForWebsiteToLoad();55 }56 @Test57 public void setGeolocationTest() throws InterruptedException {58 String getLocationLocator = "//*[@id=\"content\"]/div/button";59 driver.get("https://the-internet.herokuapp.com/geolocation");60 MessageBuilder simulateLocation = Messages.overrideLocation();61 driver.executeCdpCommand(simulateLocation.method, simulateLocation.params);62 driver.findElementByXPath(getLocationLocator).click();63 waitForWebsiteToLoad();64 }65 @Test66 public void mockWebResponseTest() throws InterruptedException {67 devTools.createSession();68 devTools.send(69 enable(Optional.of(100000000), Optional.empty(), Optional.empty()));70 devTools71 .addListener(requestIntercepted(),72 requestIntercepted -> devTools.send(continueInterceptedRequest(73 requestIntercepted.getInterceptionId(), Optional.empty(),74 Optional.of("This is Mocked!!!!!"), Optional.empty(),75 Optional.empty(), Optional.empty(), Optional.empty(),76 Optional.empty())));77 RequestPattern requestPattern = new RequestPattern("*",78 ResourceType.Document, InterceptionStage.HeadersReceived);79 devTools.send(setRequestInterception(ImmutableList.of(requestPattern)));80 driver.navigate().to("http://petstore.swagger.io/v2/swagger.json");81 waitForWebsiteToLoad();82 }83 @Test84 public void loadInsecureWebsiteTest() {85 devTools.send(Security.enable());86 devTools.send(setIgnoreCertificateErrors(false));87 driver.get("https://google.com/");88 devTools.send(Security.disable());89 waitForWebsiteToLoad();90 }91 @Test92 public void performanceTest() {93 devTools.createSession();94 devTools.send(Performance.setTimeDomain(TimeDomain.timeTicks));95 devTools.send(Performance.enable());96 System.out.println(devTools.send(Performance.getMetrics()));97 driver.get("http://www.facebook.com");98 devTools.close();99 }100 @After101 public void teardown() {102 driver.close();103 driver.quit();104 }105 @Before106 public void setUp() {107 System.setProperty("webdriver.chrome.driver",108 System.getProperty("os.name").toLowerCase().contains("windows")109 ? Paths.get(System.getProperty("user.home")).resolve("Downloads")110 .resolve("chromedriver.exe").toAbsolutePath().toString()...
Source:ChromeDevToolsFetchTest.java
...44 devTools.addListener(45 requestPaused(),46 p -> {47 Assert.assertNotNull(p);48 devTools.send(49 fulfillRequest(50 p.getRequestId(),51 204,52 Optional.of(p.getResponseHeaders().get()),53 Optional.empty(),54 Optional.empty(),55 Optional.empty()));56 });57 List<RequestPattern> patterns = new ArrayList<>();58 patterns.add(new RequestPattern(59 Optional.of("*://*.*"),60 Optional.of(ResourceType.DOCUMENT),61 Optional.of(RequestStage.REQUEST)));62 devTools.send(enable(Optional.of(patterns), Optional.empty()));63 chromeDriver.get(appServer.whereIs("simpleTest.html"));64 }65 @Test66 public void testContinueRequest() {67 devTools.addListener(68 requestPaused(),69 p -> {70 Assert.assertNotNull(p);71 devTools.send(72 continueRequest(73 p.getRequestId(),74 Optional.of(appServer.whereIs("simpleTest.html")),75 Optional.of("GET"),76 Optional.empty(),77 Optional.of(p.getRequest().getHeaders().entrySet().stream().map(e -> new HeaderEntry(e.getKey(), e.getValue().toString())).collect(78 Collectors.toList()))));79 Fetch.GetResponseBodyResponse body = devTools.send(getResponseBody(p.getRequestId()));80 Assert.assertNotNull(body);81 StreamHandle stream = devTools.send(takeResponseBodyAsStream(p.getRequestId()));82 Assert.assertNotNull(stream);83 });84 List<RequestPattern> patterns = new ArrayList<>();85 patterns.add(new RequestPattern(86 Optional.of("*://*.*"),87 Optional.of(ResourceType.DOCUMENT),88 Optional.of(RequestStage.REQUEST)));89 devTools.send(enable(Optional.of(patterns), Optional.empty()));90 chromeDriver.get(appServer.whereIs("simpleTest.html"));91 chromeDriver.get(appServer.whereIs("simpleTest.html"));92 chromeDriver.get(appServer.whereIs("simpleTest.html"));93 }94 @Test95 public void testFailRequest() {96 devTools.addListener(97 requestPaused(),98 p -> {99 Assert.assertNotNull(p);100 devTools.send(failRequest(p.getRequestId(), ErrorReason.BLOCKEDBYCLIENT));101 });102 List<RequestPattern> patterns = new ArrayList<>();103 patterns.add(new RequestPattern(104 Optional.of("*://*.*"),105 Optional.of(ResourceType.DOCUMENT),106 Optional.of(RequestStage.REQUEST)));107 devTools.send(enable(Optional.of(patterns), Optional.empty()));108 chromeDriver.get(appServer.whereIs("simpleTest.html"));109 }110}...
Source:ChromeDevToolsProfilerTest.java
...56 }57 }58 @Test59 public void sampleGetBestEffortProfilerTest() {60 devTools.send(enable());61 driver.get(appServer.whereIs("devToolsProfilerTest.html"));62 devTools.send(setSamplingInterval(30));63 List<ScriptCoverage> bestEffort = devTools.send(getBestEffortCoverage());64 assertNotNull(bestEffort);65 assertFalse(bestEffort.isEmpty());66 devTools.send(disable());67 }68 @Test69 public void sampleSetStartPreciseCoverageTest() {70 devTools.send(enable());71 driver.get(appServer.whereIs("devToolsProfilerTest.html"));72 devTools.send(startPreciseCoverage(Optional.of(true), Optional.of(true), Optional.empty()));73 devTools.send(start());74 Profiler.TakePreciseCoverageResponse pc = devTools.send(takePreciseCoverage());75 assertNotNull(pc);76 Profile profiler = devTools.send(stop());77 validateProfile(profiler);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}...
Source:DevToolsApiUtils.java
...21 */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}...
send
Using AI Code Generation
1import org.openqa.selenium.devtools.DevTools;2import org.openqa.selenium.devtools.v91.network.Network;3import org.openqa.selenium.devtools.v91.network.model.Headers;4import org.openqa.selenium.devtools.v91.network.model.RequestPattern;5import org.openqa.selenium.devtools.v91.network.model.ResourceType;6public class DevToolsDemo {7 public static void main(String[] args) {8 DevTools devTools = driver.getDevTools();9 devTools.createSession();10 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));11 devTools.send(Network.setRequestInterception(12 Collections.singletonList(13 RequestPattern.builder()14 .setResourceType(ResourceType.DOCUMENT)15 .build())));16 devTools.addListener(Network.requestIntercepted(), request -> {17 devTools.send(Network.continueInterceptedRequest(request.getRequestId(),18 Optional.of(new Headers()),19 Optional.empty()));20 });21 }22}
send
Using AI Code Generation
1import org.openqa.selenium.devtools.DevTools;2import org.openqa.selenium.devtools.v91.log.Log;3import org.openqa.selenium.devtools.v91.log.model.LogEntry;4public class DevToolsTest {5 public static void main(String[] args) {6 WebDriver driver = new FirefoxDriver();7 DevTools devTools = ((ChromeDriver) driver).getDevTools();8 devTools.createSession();9 devTools.send(Log.enable());10 devTools.addListener(Log.entryAdded(), (LogEntry logEntry) -> {11 System.out.println(logEntry.getText());12 });13 }14}
send
Using AI Code Generation
1WebDriver driver = new ChromeDriver();2DevTools devTools = ((ChromeDriver) driver).getDevTools();3devTools.createSession();4String targetId = devTools.getRemote().send("Target.getCurrentTarget").getValue().get("targetId").getAsString();5devTools.send("Page.enable");6String base64EncodedPng = devTools.send("Page.captureScreenshot", ImmutableMap.of("format", "png", "fromSurface", true)).getValue().get("data").getAsString();7byte[] decodedPng = Base64.getDecoder().decode(base64EncodedPng);8FileUtils.writeByteArrayToFile(new File("screenshot.png"), decodedPng);9devTools.close();10driver.quit();
send
Using AI Code Generation
1DevTools devTools = driver.getDevTools();2devTools.createSession();3Command command = new Command("Network.enable", null);4devTools.send(command);5Command command = new Command("Network.setCacheDisabled", ImmutableMap.of("cacheDisabled", true));6devTools.send(command);7Command command = new Command("Network.setExtraHTTPHeaders", ImmutableMap.of("headers", ImmutableMap.of("User-Agent", "Chrome")));8devTools.send(command);9devTools.send(command);10Command command = new Command("Network.setCookies", ImmutableMap.of("cookies", Arrays.asList(ImmutableMap.of("name", "foo", "value", "bar"))));11devTools.send(command);12Command command = new Command("Network.setBypassServiceWorker", ImmutableMap.of("bypass", true));13devTools.send(command);14Command command = new Command("Network.setBypassCSP", ImmutableMap.of("bypass", true));15devTools.send(command);16Command command = new Command("Network.setUserAgentOverride", ImmutableMap.of("userAgent", "Chrome"));17devTools.send(command);18Command command = new Command("Network.setAcceptLanguageOverride", ImmutableMap.of("acceptLanguage", "en-US"));19devTools.send(command);20Command command = new Command("Network.setDownloadBehavior", ImmutableMap.of("behavior", "allow", "downloadPath", "/tmp"));21devTools.send(command);22devTools.send(command
send
Using AI Code Generation
1ChromeDriver driver = new ChromeDriver();2DevTools devTools = driver.getDevTools();3devTools.createSession();4devTools.send(new Command<>("Page.navigate", ImmutableMap.of(5driver.quit();6ChromeDriver driver = new ChromeDriver();7DevTools devTools = driver.getDevTools();8devTools.createSession();9devTools.send(new Command<>("Page.navigate", ImmutableMap.of(10driver.quit();11ChromeDriver driver = new ChromeDriver();12DevTools devTools = driver.getDevTools();13devTools.createSession();14devTools.send(new Command<>("Page.navigate", ImmutableMap.of(15driver.quit();16ChromeDriver driver = new ChromeDriver();17DevTools devTools = driver.getDevTools();18devTools.createSession();19devTools.send(new Command<>("Page.navigate", ImmutableMap.of(20driver.quit();21ChromeDriver driver = new ChromeDriver();22DevTools devTools = driver.getDevTools();23devTools.createSession();24devTools.send(new Command<>("Page.navigate", ImmutableMap.of
send
Using AI Code Generation
1import static java.util.concurrent.TimeUnit.SECONDS;2import static org.openqa.selenium.devtools.DevTools.send;3import static org.openqa.selenium.devtools.network.Network.enable;4import static org.openqa.selenium.devtools.network.model.ConnectionType.CELLULAR2G;5import org.openqa.selenium.devtools.DevTools;6import org.openqa.selenium.devtools.network.Network;7import org.openqa.selenium.devtools.network.model.ConnectionType;8import org.openqa.selenium.devtools.network.model.ConnectionTypeChanged;9import io.github.bonigarcia.wdm.WebDriverManager;10public class DevToolsTest {11 public static void main(String[] args) {12 WebDriverManager.chromedriver().setup();13 ChromeDriver driver = new ChromeDriver();14 driver.manage().timeouts().implicitlyWait(10, SECONDS);15 DevTools devTools = driver.getDevTools();16 devTools.createSession();17 devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));18 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 1000, Optional.of(ConnectionType.CELLULAR2G)));19 devTools.addListener(Network.connectionTypeChanged(), (ConnectionTypeChanged connectionTypeChanged) -> {20 System.out.println(connectionTypeChanged.getConnectionType());21 });22 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 1000, Optional.of(ConnectionType.WIFI)));23 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 1000, Optional.of(ConnectionType.CELLULAR2G)));24 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 1000, Optional.of(ConnectionType.WIFI)));25 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 1000, Optional.of(ConnectionType.CELLULAR2G)));26 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 1000, Optional.of(ConnectionType.WIFI)));27 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 1000, Optional.of(ConnectionType.CELLULAR2G)));
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.
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.
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.
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.
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.
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.
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.
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.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!