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

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

Source:DevToolsTest.java Github

copy

Full Screen

...37 // Доступ к DevTools38 ChromeDriver chrome = (ChromeDriver) driver;39 DevTools devTools = chrome.getDevTools();40 // Открытие сессии DevTools41 devTools.createSession();42 // Предоставление прав браузеру на выполнение операций43 // Browser.grantPermissions - предоставление прав браузеру44 // Список предоставляемых прав45 List<PermissionType> permissions = new ArrayList<>();46 permissions.add(PermissionType.AUDIOCAPTURE);47 permissions.add(PermissionType.VIDEOCAPTURE);48 permissions.add(PermissionType.GEOLOCATION);49 devTools.send(Browser.grantPermissions(permissions, Optional.empty(), Optional.empty()));50 // Открыть страницу yandex.ru51 chrome.get("https://yandex.ru");52 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");53 try {54 Thread.sleep(10000);55 } catch (InterruptedException e) {56 e.printStackTrace();57 }58 // Закрытие сессии DevTools59 devTools.close();60 }61 @Test62 public void browserVersionTest() {63 // Доступ к DevTools64 ChromeDriver chrome = (ChromeDriver) driver;65 DevTools devTools = chrome.getDevTools();66 // Открытие сессии DevTools67 devTools.createSession();68 // Получение данных о браузере69 // Browser.getVersion - получение данных о версии70 Browser.GetVersionResponse version = devTools.send(Browser.getVersion());71 // Вывод данных о браузере72 logger.info("Browser: " + version.getProduct());73 logger.info("User Agent: " + version.getUserAgent());74 logger.info("JS: " + version.getJsVersion());75 logger.info("Protocol: " + version.getProtocolVersion());76 // Открыть страницу yandex.ru77 chrome.get("https://yandex.ru");78 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");79 try {80 Thread.sleep(10000);81 } catch (InterruptedException e) {82 e.printStackTrace();83 }84 // Закрытие сессии DevTools85 devTools.close();86 }87 @Test88 public void emulationSetDeviceMetricsTest() {89 // Доступ к DevTools90 ChromeDriver chrome = (ChromeDriver) driver;91 DevTools devTools = chrome.getDevTools();92 // Открытие сессии DevTools93 devTools.createSession();94 // Установка параметров эмулируемого устройства95 // Emulation.setDeviceMetricsOverride - установка параметров96 // Параметры эмулируемого устройства97 int width = 600; // Ширина98 int height = 1000; // Высота99 int deviceScaleFactor = 50; //100 boolean mobile = false; // Мобильное устройство101 devTools.send(Emulation.setDeviceMetricsOverride(102 width, height, deviceScaleFactor, mobile,103 Optional.empty(), Optional.empty(), Optional.empty(),104 Optional.empty(), Optional.empty(), Optional.empty(),105 Optional.empty(), Optional.empty(), Optional.empty())106 );107 // Открыть страницу yandex.ru108 chrome.get("https://yandex.ru");109 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");110 logger.info("Параметры экрана");111 logger.info("Ширина: " + chrome.executeScript("return document.documentElement.clientWidth"));112 logger.info("Высота: " + chrome.executeScript("return document.documentElement.clientHeight"));113 try {114 Thread.sleep(10000);115 } catch (InterruptedException e) {116 e.printStackTrace();117 }118 // Закрытие сессии DevTools119 devTools.close();120 }121 @Test122 public void emulationSetGeoLocationTest() {123 // Доступ к DevTools124 ChromeDriver chrome = (ChromeDriver) driver;125 DevTools devTools = chrome.getDevTools();126 // Открытие сессии DevTools127 devTools.createSession();128 // Установка геолокации129 // Emulation.setGeolocationOverride - установка геолокации130 // Параметры геолокации131 Optional<Number> latitude = Optional.of(50.52930); // Широта132 Optional<Number> longitude = Optional.of(42.68620); // Долгота133 Optional<Number> accuracy = Optional.of(10); // Точность134 devTools.send(Emulation.setGeolocationOverride(latitude, longitude, accuracy));135 // Открыть страницу mycurrentlocation.net136 chrome.get("https://mycurrentlocation.net/");137 logger.info("Открыта страница mycurrentlocation.net - " + "https://mycurrentlocation.net/");138 try {139 Thread.sleep(10000);140 } catch (InterruptedException e) {141 e.printStackTrace();142 }143 // Закрытие сессии DevTools144 devTools.close();145 }146 @Test147 public void logListenerTest() {148 // Доступ к DevTools149 ChromeDriver chrome = (ChromeDriver) driver;150 DevTools devTools = chrome.getDevTools();151 // Открытие сессии DevTools152 devTools.createSession();153 // Вывод логов154 // Log.enable - включение доступа к логам155 devTools.send(Log.enable());156 // Слушатель157 devTools.addListener(Log.entryAdded(),158 // Вывод логов159 logEntry -> {160 logger.info("Log: " + logEntry.getText());161 logger.info("Level: " + logEntry.getLevel());162 }163 );164 // Открыть страницу yandex.ru165 chrome.get("https://yandex.ru");166 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");167 // Ввести в строку поиска текст - Selenium168 WebElement input = chrome.findElement(By.xpath("//input[@class=\"input__control input__input mini-suggest__input\"]"));169 input.sendKeys("Selenium");170 // Нажать на кнопку "Найти"171 WebElement button = chrome.findElement(By.xpath("//button[@class=\"button mini-suggest__button button_theme_search button_size_search i-bem button_js_inited\"]"));172 button.click();173 try {174 Thread.sleep(10000);175 } catch (InterruptedException e) {176 e.printStackTrace();177 }178 // Закрытие сессии DevTools179 devTools.close();180 }181 @Test182 public void performanceMetricsTest() {183 // Доступ к DevTools184 ChromeDriver chrome = (ChromeDriver) driver;185 DevTools devTools = chrome.getDevTools();186 // Открытие сессии DevTools187 devTools.createSession();188 // Сбор метрик189 // Performance.enable - включение сбора метрик190 devTools.send(Performance.enable(Optional.of(Performance.EnableTimeDomain.TIMETICKS)));191 // Открыть страницу yandex.ru192 chrome.get("https://yandex.ru");193 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");194 // Ввести в строку поиска текст - Selenium195 WebElement input = chrome.findElement(By.xpath("//input[@class=\"input__control input__input mini-suggest__input\"]"));196 input.sendKeys("Selenium");197 // Нажать на кнопку "Найти"198 WebElement button = chrome.findElement(By.xpath("//button[@class=\"button mini-suggest__button button_theme_search button_size_search i-bem button_js_inited\"]"));199 button.click();200 try {201 Thread.sleep(10000);202 } catch (InterruptedException e) {203 e.printStackTrace();204 }205 // Получение метрик206 List<Metric> metrics = devTools.send(Performance.getMetrics());207 List<String> metricNames = metrics.stream()208 .map(o -> o.getName())209 .collect(Collectors.toList());210 // Performance.disable - выключение сбора метрик211 devTools.send(Performance.disable());212 // Список метрик для проверки213 List<String> metricsToCheck = Arrays.asList(214 "Timestamp",215 "Documents",216 "Frames",217 "JSEventListeners",218 "LayoutObjects",219 "MediaKeySessions",220 "Nodes",221 "Resources",222 "DomContentLoaded",223 "NavigationStart"224 );225 // Вывод метрик226 metricsToCheck.forEach(metric ->227 logger.info(metric + " is : " + metrics.get(metricNames.indexOf(metric)).getValue())228 );229 // Закрытие сессии DevTools230 devTools.close();231 }232 @Test233 public void fetchRequestsTest() {234 // Доступ к DevTools235 ChromeDriver chrome = (ChromeDriver) driver;236 DevTools devTools = chrome.getDevTools();237 // Открытие сессии DevTools238 devTools.createSession();239 // Перехват запроса240 // Fetch.enable - включение перехвата запроса241 devTools.send(Fetch.enable(Optional.empty(), Optional.empty()));242 // Слушатель243 devTools.addListener(244 // Fetch.requestPaused - остановка запроса245 Fetch.requestPaused(),246 // Обработка запроса247 request -> {248 // Новый URL запроса (подставляем в Fetch.continueRequest)249 String newUrl = request.getRequest().getUrl().contains("yandex.ru")250 ? request.getRequest().getUrl().replace("yandex.ru", "ya.ru")251 : request.getRequest().getUrl();252 // Параметры запроса253 RequestId requestId = request.getRequestId(); // ID запроса254 Optional<String> url = Optional.of(request.getRequest().getUrl()); // URL запроса255 Optional<String> method = Optional.of(request.getRequest().getMethod()); // Метод запроса256 Optional<String> postData = request.getRequest().getPostData(); // Данные POST запроса257 Optional<List<HeaderEntry>> headers = request.getResponseHeaders(); // Заголовки запроса258 // Fetch.continueRequest - продолжение запроса259 devTools.send(Fetch.continueRequest(requestId, url, method, postData, headers));260 }261 );262 // Открыть страницу yandex.ru263 chrome.get("https://yandex.ru");264 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");265 // Ввести в строку поиска текст - Selenium266 WebElement input = chrome.findElement(By.xpath("//input[@class=\"input__control input__input mini-suggest__input\"]"));267 input.sendKeys("Selenium");268 // Нажать на кнопку "Найти"269 WebElement button = chrome.findElement(By.xpath("//button[@class=\"button mini-suggest__button button_theme_search button_size_search i-bem button_js_inited\"]"));270 button.click();271 try {272 Thread.sleep(10000);273 } catch (InterruptedException e) {274 e.printStackTrace();275 }276 // Закрытие сессии DevTools277 devTools.close();278 }279 @Test280 public void networkConnectEmulationTest() {281 // Доступ к DevTools282 ChromeDriver chrome = (ChromeDriver) driver;283 DevTools devTools = chrome.getDevTools();284 // Открытие сессии DevTools285 devTools.createSession();286 // Эмуляция интернет соединения287 // Network.enable - включение сетевых возможностей288 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));289 // Network.emulateNetworkConditions - эмуляция интернет соединения290 // Параметры соединения291 Boolean offline = false; // Оффлайн режим292 Number latency = 2; // Задержка293 Number downloadThroughput = 80000; // Пропускная способность скачивания294 Number uploadThroughput = 200000; // Пропускная способность загрузки295 Optional<ConnectionType> connectionType = Optional.of(ConnectionType.CELLULAR2G); // Тип соединения296 devTools.send(Network.emulateNetworkConditions(offline, latency, downloadThroughput, uploadThroughput, connectionType));297 // Открыть страницу yandex.ru298 chrome.get("https://yandex.ru");299 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");300 // Ввести в строку поиска текст - Selenium301 WebElement input = chrome.findElement(By.xpath("//input[@class=\"input__control input__input mini-suggest__input\"]"));302 input.sendKeys("Selenium");303 // Нажать на кнопку "Найти"304 WebElement button = chrome.findElement(By.xpath("//button[@class=\"button mini-suggest__button button_theme_search button_size_search i-bem button_js_inited\"]"));305 button.click();306 try {307 Thread.sleep(10000);308 } catch (InterruptedException e) {309 e.printStackTrace();310 }311 // Закрытие сессии DevTools312 devTools.close();313 }314 @Test315 public void networkAddHeadersTest() {316 // Доступ к DevTools317 ChromeDriver chrome = (ChromeDriver) driver;318 DevTools devTools = chrome.getDevTools();319 // Открытие сессии DevTools320 devTools.createSession();321 // Добавление заголовков в запросы322 // Network.enable - включение сетевых возможностей323 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));324 // Network.setExtraHTTPHeaders - отправка заголовков запроса325 // Заголовки326 Map<String, Object> headers = new HashMap<>();327 headers.put("headername1", "headervalue1");328 devTools.send(Network.setExtraHTTPHeaders(new Headers(headers)));329 // Слушатель330 devTools.addListener(331 // Network.requestWillBeSent - перехват запроса332 Network.requestWillBeSent(),333 // Обработка запроса334 request -> {335 if (request.getRequest().getHeaders().get("headername1").equals("headervalue1"))336 logger.info("URL: " + request.getRequest().getUrl() +337 "\nHeaders: " + request.getRequest().getHeaders());338 }339 );340 // Открыть страницу yandex.ru341 chrome.get("https://yandex.ru");342 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");343 try {344 Thread.sleep(10000);345 } catch (InterruptedException e) {346 e.printStackTrace();347 }348 // Закрытие сессии DevTools349 devTools.close();350 }351 @Test352 public void networkCaptureHttpRequestTest() {353 // Доступ к DevTools354 ChromeDriver chrome = (ChromeDriver) driver;355 DevTools devTools = chrome.getDevTools();356 // Открытие сессии DevTools357 devTools.createSession();358 // Перехват HTTP запроса359 // Network.enable - включение сетевых возможностей360 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));361 // Слушатель362 devTools.addListener(363 // Network.requestWillBeSent - перехват запроса364 Network.requestWillBeSent(),365 // Обработка запроса366 request -> {367 if (request.getRequest().getUrl().contains("zen.yandex"))368 logger.info(request.getRequest().getMethod() + " " + request.getRequest().getUrl());369 }370 );371 // Открыть страницу yandex.ru372 chrome.get("https://yandex.ru");373 logger.info("Открыта страница yandex.ru - " + "https://yandex.ru");374 try {375 Thread.sleep(10000);376 } catch (InterruptedException e) {377 e.printStackTrace();378 }379 // Закрытие сессии DevTools380 devTools.close();381 }382 @Test383 public void networkBasicAuthTest() {384 // Доступ к DevTools385 ChromeDriver chrome = (ChromeDriver) driver;386 DevTools devTools = chrome.getDevTools();387 // Открытие сессии DevTools388 devTools.createSession();389 // Авторизация BasicAuth390 // Network.enable - включение сетевых возможностей391 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));392 // Открыть страницу jigsaw.w3.org/HTTP/393 driver.get("https://jigsaw.w3.org/HTTP/");394 logger.info("Открыта страница jigsaw.w3.org/HTTP/ - " + "https://jigsaw.w3.org/HTTP/");395 // Отправка заголовков396 // Network.setExtraHTTPHeaders - отправка заголовков запроса397 final String USERNAME = "guest"; // Имя пользователя398 final String PASSWORD = "guest"; // Пароль пользователя399 byte[] encodedUserPass = new Base64().encode(String.format("%s:%s", USERNAME, PASSWORD).getBytes());400 String basicAuth = "Basic " + new String(encodedUserPass);401 Map<String, Object> headers = new HashMap<>(); // Заголовки402 headers.put("Authorization", basicAuth);...

Full Screen

Full Screen

Source:Selenium4ChromeDevToolsTest.java Github

copy

Full Screen

...42 @Test43 public void allowExpiredCertificates() {44 //initiate devtools45 DevTools devtools = ((ChromeDriver) driver).getDevTools();46 devtools.createSession();47 devtools.send(Security.setIgnoreCertificateErrors(Boolean.TRUE));48 driver.get("https://expired.badssl.com/");49 WebElement expiredLabel = driver.findElement(By.tagName("h1"));50 System.out.println(expiredLabel.getText());51 waitAbit(5);52 }53 @Test54 public void listenToConsole() {55 //initiate devtools56 DevTools devtools = ((ChromeDriver) driver).getDevTools();57 devtools.createSession();58 devtools.getDomains().log().enable();59 devtools.getDomains().events()60 .addConsoleListener(consoleEvent -> System.out.println(consoleEvent.toString()));61 driver.get("http://bdd.atlasid.tech/");62 waitAbit(10);63 }64 @Test65 public void blockingRequest() {66 //initiate devtools67 DevTools devtools = ((ChromeDriver) driver).getDevTools();68 devtools.createSession();69 devtools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));70 devtools.send(Network.setBlockedURLs(ImmutableList71 .of("https://api.mygostore.com/*",72 "*.css", "*.jpg", "*.jpeg")));73 driver.get("https://japfabest.mygostore.com/");74 waitAbit(5);75 }76 @Test77 public void setGeoLocationTest() {78 //initiate devtools79 DevTools devtools = ((ChromeDriver) driver).getDevTools();80 devtools.createSession();81 devtools.send(Emulation82 .setGeolocationOverride(Optional.of(53.46471543617865), Optional.of(-2.291327904828742),83 Optional.of(100)));84 driver.get("http://maps.google.com/");85 waitAbit(4);86 WebElement buttonYourLocation = driver87 .findElement(By.xpath("//button[contains(@id,'mylocation')]"));88 buttonYourLocation.click();89 waitAbit(10);90 }91 @Test92 public void setTimezoneTest() {93 //initiate devtools94 DevTools devtools = ((ChromeDriver) driver).getDevTools();95 devtools.createSession();96 devtools.send(Emulation.setTimezoneOverride("Europe/Amsterdam"));97 driver.get("https://webbrowsertools.com/timezone/");98 waitAbit(10);99 }100 @Test101 public void emulate2GNetwork() {102 //initiate devtools103 DevTools devtools = ((ChromeDriver) driver).getDevTools();104 devtools.createSession();105 devtools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));106 //set 40kilobyte/s for upload/download, latency 5000 m/s107 devtools.send(Network.emulateNetworkConditions(Boolean.FALSE, 5000, 40000, 40000, Optional.of(108 ConnectionType.CELLULAR2G)));109 driver.get("https://www.tokopedia.com/");110 waitAbit(20);111 }112 @Test113 public void emulateOfflineNetwork() {114 //initiate devtools115 DevTools devtools = ((ChromeDriver) driver).getDevTools();116 devtools.createSession();117 devtools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));118 //set 10megabyte/s for upload/download, latency 10 m/s119 driver.get("https://www.google.com/");120 devtools121 .send(Network.emulateNetworkConditions(Boolean.TRUE, 10, 10000000, 10000000, Optional.of(122 ConnectionType.CELLULAR4G)));123 driver.navigate().refresh();124 waitAbit(10);125 }126 @Test127 public void clearBrowsingCache() {128 //initiate devtools129 DevTools devtools = ((ChromeDriver) driver).getDevTools();130 devtools.createSession();131 driver.get("https://refreshyourcache.com/en/cache-test/");132 devtools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));133 devtools.send(Network.clearBrowserCache());134 devtools.send(Network.setCacheDisabled(Boolean.TRUE));135 driver.navigate().refresh();136 waitAbit(10);137 }138 @Test139 public void clearCookies() {140 //initiate devtools141 DevTools devtools = ((ChromeDriver) driver).getDevTools();142 devtools.createSession();143 devtools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));144 driver.get("http://bdd.atlasid.tech/");145 driver.manage().addCookie(new Cookie("test", "test"));146 devtools.send(Network.clearBrowserCookies());147 waitAbit(20);148 }149 @Test150 public void interceptNetworkAndChangeResponse() {151 //initiate devtools152 DevTools devtools = ((ChromeDriver) driver).getDevTools();153 devtools.createSession();154 devtools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));155 driver.get("https://japfabest.mygostore.com/");156 devtools.getDomains().network().addRequestHandler(157 httpRequest -> httpRequest.getUri().contains("api.mygostore.com/catalog/v1/outlet"),158 httpRequest -> {159 HttpResponse response = new HttpResponse();160 response.setStatus(200);161 response162 .setContent(() -> new ByteArrayInputStream("{\"total\":0,\"content\":[]}".getBytes(163 StandardCharsets.UTF_8)));164 return response;165 });166 driver.navigate().refresh();167 waitAbit(20);168 }169 @Test170 public void listenNetwork() {171 //initiate devtools172 DevTools devtools = ((ChromeDriver) driver).getDevTools();173 devtools.createSession();174 devtools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));175 devtools.addListener(Network.requestWillBeSent(), entry -> {176 if (entry.getRequest().getUrl().contains("api.mygostore.com/catalog/v1/outlet")) {177 System.out.println("Request (id) URL : (" + entry.getRequestId() + ") "178 + entry.getRequest().getUrl()179 + " (" + entry.getRequest().getMethod() + ")");180 }181 });182 devtools.addListener(Network.responseReceived(), entry -> {183 if (entry.getResponse().getUrl().contains("api.mygostore.com/catalog/v1/outlet")) {184 System.out.println("Response (Req id) URL : (" + entry.getRequestId() + ") "185 + entry.getResponse().getUrl()186 + " (" + entry.getResponse().getStatus() + ")");187 GetResponseBodyResponse body = devtools...

Full Screen

Full Screen

Source:DevToolsApiUtils.java Github

copy

Full Screen

...20 * To view Console Logs21 */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

Source:ChromeDevTools.java Github

copy

Full Screen

...27 driver = new ChromeDriver();28 29 DevTools devTools = ((ChromiumDriver) driver).getDevTools();30 31 devTools.createSession();32 33 devTools.send(Network.enable(Optional.empty(),Optional.empty(),Optional.empty()));34 devTools.send(Network.emulateNetworkConditions(true, 100, 1000, 2000, Optional.of(ConnectionType.WIFI)));35 36 devTools.addListener(Network.loadingFailed(), loadingFailed -> assertEquals(loadingFailed.getErrorText(), "net:: ERR_INTERNET_DISCONNECTED"));37 driver.get("https://github.com");38 39 driver.quit();40 }41 42 @Test(priority=2, description="Make the Network Online")43 public void EnableNetworkOnline() {44 WebDriverManager.chromedriver().setup();45 driver = new ChromeDriver();46 47 DevTools devTools = ((ChromiumDriver) driver).getDevTools();48 49 devTools.createSession();50 51 devTools.send(Network.enable(Optional.empty(),Optional.empty(),Optional.empty()));52 devTools.send(Network.emulateNetworkConditions(false, 100, 1000, 2000, Optional.of(ConnectionType.WIFI)));53 54 driver.get("https://demo.nopcommerce.com/");55 56 driver.quit();57 }58 59 @Test(priority=3, description="Get Console Logs")60 public void GetConsoleLogs() {61 WebDriverManager.chromedriver().setup();62 driver = new ChromeDriver();63 64 DevTools devTools = ((ChromiumDriver) driver).getDevTools();65 66 devTools.createSession();67 68 devTools.send(Log.enable());69 70 /*devTools.addListener(Log.entryAdded(), logEntry -> {71 System.out.println(logEntry.getText());72 System.out.println(logEntry.getLevel());73 });*/74 75 //devTools.addListener(Log.entryAdded(), entry ->entry.getText());76 ((RemoteWebDriver) driver).setLogLevel(Level.INFO);77 //driver.get("https://google.com/");78 driver.get("https://demo.nopcommerce.com/");79 80 driver.quit();81 }82 83 @Test(priority=4, description = "Load Unsecured Website")84 public void LoadUnsecuredWebsite() {85 WebDriverManager.chromedriver().setup();86 driver = new ChromeDriver();87 88 DevTools devTools = ((ChromiumDriver) driver).getDevTools();89 90 devTools.createSession();91 92 devTools.send(Security.setIgnoreCertificateErrors(true));93 94 driver.get("https://expired.badss1.com/");95 96 driver.quit();97 98 }99 100 }101 ...

Full Screen

Full Screen

Source:ChromeDevToolsDemo.java Github

copy

Full Screen

...20 public void enableNetworkOffline() {21 WebDriverManager.chromedriver().setup();22 driver=new ChromeDriver();23 DevTools devTools=((ChromiumDriver)driver).getDevTools();24 devTools.createSession();25 devTools.send(Network.enable(Optional.of(1000000),Optional.empty(),Optional.empty()));26 devTools.send(emulateNetworkConditions(true,100,1000,2000,Optional.of(ConnectionType.WIFI)));27 driver.get("https://formy-project.herokuapp.com/");28 }29 @Test(description = "Get console logs")30 public void generateConsoleLogs() {31 WebDriverManager.chromedriver().setup();32 driver=new ChromeDriver();33 DevTools devTools=((ChromiumDriver)driver).getDevTools();34 devTools.createSession();35 devTools.send(Log.enable());36// devTools.addListener(Log.entryAdded(),entry -> System.out.println(entry.asSeleniumLogEntry()));37 driver.get("https://formy-project.herokuapp.com/");38 }39}...

Full Screen

Full Screen

Source:Issue9803.java Github

copy

Full Screen

...17 WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444"), new ChromeOptions());18 driver = new Augmenter().augment(driver);19 driver.get("https://www.duckduckgo.com");20 DevTools devTools = ((HasDevTools) driver).getDevTools();21 devTools.createSession();22 devTools.send(Log.enable());23 devTools.send(Browser.setWindowBounds(new WindowID(1), new Bounds(24 Optional.of(20),25 Optional.of(20),26 Optional.of(20),27 Optional.of(20),28 Optional.of(WindowState.NORMAL))));29 driver.quit();30 }31}...

Full Screen

Full Screen

Source:Test167.java Github

copy

Full Screen

...16 ChromeDriver driver=new ChromeDriver();17 driver.manage().window().maximize();18 //Create DevTools session19 DevTools dt=driver.getDevTools();20 dt.createSession();21 //Set blocked URL patterns22 Command cmd1=Network.enable(Optional.empty(),Optional.empty(),Optional.empty());23 Command cmd2=new Command("Emulation.setTimezoneOverride",ImmutableMap.of("timezoneId","PST"));24 dt.send(cmd1);25 dt.send(cmd2);26 //Launch site27 driver.get("https://momentjs.com");28 //close site29 //driver.close();30 }31}...

Full Screen

Full Screen

Source:Test166.java Github

copy

Full Screen

...16 ChromeDriver driver=new ChromeDriver();17 driver.manage().window().maximize();18 //Create DevTools session19 DevTools dt=driver.getDevTools();20 dt.createSession();21 //Set blocked URL patterns22 Command cmd1=Network.enable(Optional.empty(),Optional.empty(),Optional.empty());23 Command cmd2=Network.setBlockedURLs(ImmutableList.of("*.css","*.png","*.gif"));24 dt.send(cmd1);25 dt.send(cmd2);26 //Launch site27 driver.get("http://www.redbus.in");28 //close site29 //driver.close();30 }31}...

Full Screen

Full Screen

createSession

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.devtools.DevTools;2import org.openqa.selenium.devtools.v91.browser.Browser;3import org.openqa.selenium.devtools.v91.browser.model.BrowserContextID;4import org.openqa.selenium.devtools.v91.browser.model.WindowID;5import org.openqa.selenium.devtools.v91.network.Network;6import org.openqa.selenium.devtools.v91.network.model.ConnectionType;7import org.openqa.selenium.devtools.v91.network.model.ConnectionTypeEnum;8import org.openqa.selenium.devtools.v91.network.model.RequestPattern;9import org.openqa.selenium.devtools.v91.network.model.ResourceType;10import org.openqa.selenium.devtools.v91.network.model.ResourceTypeEnum;11import org.openqa.selenium.devtools.v91.page.Page;12import org.openqa.selenium.devtools.v91.page.model.FrameId;13import org.openqa.selenium.devtools.v91.page.model.Viewport;14import org.openqa.selenium.devtools.v91.target.Target;15import org.openqa.selenium.devtools.v91.target.model.BrowserContextID;16import org.openqa.selenium.devtools.v91.target.model.TargetInfo;17import org.openqa.selenium.devtools.v91.target.model.TargetInfoChanged;18import org.openqa.selenium.devtools.v91.target.model.TargetInfoChangedReason;19import org.openqa.selenium.devtools.v91.target.model.TargetInfoChangedReasonEnum;20import org.openqa.selenium.devtools.v91.target.model.TargetInfoChangedStatus;21import org.openqa.selenium.devtools.v91.target.model.TargetInfoChangedStatusEnum;22import org.openqa.selenium.devtools.v91.target.model.TargetInfoChangedTargetInfo;23import org.openqa.selenium.devtools.v91.target.model.TargetInfoChangedTargetInfoEnum;24import org.openqa.selenium.devtools.v91.target.model.TargetInfoEnum;25import org.openqa.selenium.devtools.v91.target.model.TargetTypeEnum;26import org.openqa.selenium.devtools.v91.target.model.TargetsCreated;27import org.openqa.selenium.devtools.v91.target.model.TargetsDestroyed;28import org.openqa.selenium.devtools.v91.target.model.TargetsInfo;29import org.openqa.selenium.devtools.v91.target.model.TargetsInfoEnum;30import org.openqa.selenium.devtools.v91.target.model.TargetsInfoTargetInfo;31import org.openqa.selenium.devtools.v91.target.model.TargetsInfoTargetInfoEnum;32import org.openqa.selenium.devtools.v91.target.model.TargetsInfoTargetInfoTargetId;33import org.openqa.selenium.devtools.v91.target.model.TargetsInfoTargetInfoTargetTypeEnum;34import org.openqa.selenium.devtools.v91.target.model.TargetsInfoTargetInfoTitle;35import org.openqa.selenium.devtools.v91.target.model.TargetsInfoTargetInfoUrl;36import

Full Screen

Full Screen

createSession

Using AI Code Generation

copy

Full Screen

1package com.codebind;2import java.util.HashMap;3import java.util.Map;4import java.util.concurrent.TimeUnit;5import java.util.logging.Level;6import java.util.logging.Logger;7import org.openqa.selenium.By;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.WebElement;10import org.openqa.selenium.chrome.ChromeDriver;11import org.openqa.selenium.devtools.DevTools;12import org.openqa.selenium.devtools.v94.network.Network;13import org.openqa.selenium.devtools.v94.network.model.ConnectionType;14import org.openqa.selenium.devtools.v94.network.model.Headers;15import org.openqa.selenium.devtools.v94.network.model.RequestPattern;16import org.openqa.selenium.devtools.v94.network.model.ResourceType;17import org.openqa.selenium.devtools.v94.network.model.SetCookieRequest;18import org.openqa.selenium.devtools.v94.page.Page;19import org.openqa.selenium.devtools.v94.page.model.Viewport;20import io.github.bonigarcia.wdm.WebDriverManager;21public class DevToolsTest {22 public static void main(String[] args) {23 WebDriverManager.chromedriver().setup();24 Logger.getLogger("").setLevel(Level.OFF);25 WebDriver driver = new ChromeDriver();26 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);27 driver.manage().window().maximize();28 DevTools devTools = ((ChromeDriver) driver).getDevTools();29 devTools.createSession();30 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));31 devTools.send(Network.emulateNetworkConditions(false, 100, 10000, 100000, Optional.empty()));32 devTools.send(Network.setCacheDisabled(true));33 devTools.send(Network.setExtraHTTPHeaders(new Headers(new HashMap<String, Object>() {34 {35 put("Accept-Language", "en-US");36 }37 })));38 devTools.send(Network.setUserAgentOverride(39 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"));40 devTools.send(Network.setBlockedURLs(new ArrayList<String>() {41 {42 }43 }));44 devTools.send(Network.setRequestInterception(true));45 devTools.addListener(Network.requestIntercepted(), request -> {

Full Screen

Full Screen

createSession

Using AI Code Generation

copy

Full Screen

1package com.test;2import org.openqa.selenium.devtools.DevTools;3import org.openqa.selenium.devtools.v95.browser.Browser;4import org.openqa.selenium.devtools.v95.browser.model.BrowserContextID;5import org.openqa.selenium.devtools.v95.browser.model.WindowID;6import org.openqa.selenium.devtools.v95.page.Page;7import org.openqa.selenium.devtools.v95.page.model.FrameID;8import org.openqa.selenium.devtools.v95.page.model.WindowFeatures;9import org.openqa.selenium.devtools.v95.target.Target;10import org.openqa.selenium.devtools.v95.target.model.TargetID;11import org.openqa.selenium.remote.RemoteWebDriver;12public class CreateSession {13 public static void main(String[] args) {14 RemoteWebDriver driver = new RemoteWebDriver();15 DevTools devTools = driver.getDevTools();16 devTools.createSession();17 devTools.send(Browser.enable());18 devTools.send(Target.setDiscoverTargets(true));19 devTools.send(Page.enable());20 devTools.send(Page.setDownloadBehavior(Page.SetDownloadBehaviorBehavior.ALLOW));21 devTools.addListener(Page.downloadWillBegin(), downloadWillBegin -> {22 System.out.println("Download will begin");23 });24 devTools.addListener(Page.downloadProgress(), downloadProgress -> {25 System.out.println("Download progress");26 });27 devTools.addListener(Page.downloadFailed(), downloadFailed -> {28 System.out.println("Download failed");29 });30 devTools.addListener(Page.downloadFinished(), downloadFinished -> {31 System.out.println("Download finished");32 });33 devTools.addListener(Target.receivedMessageFromTarget(), receivedMessageFromTarget -> {34 System.out.println("Received message from target");35 });36 devTools.addListener(Target.targetCreated(), targetCreated -> {37 System.out.println("Target created");38 });39 devTools.addListener(Target.targetDestroyed(), targetDestroyed -> {40 System.out.println("Target destroyed");41 });42 devTools.addListener(Target.targetInfoChanged(), targetInfoChanged -> {43 System.out.println("Target info changed");44 });45 devTools.addListener(Browser.attachedToTarget(), attachedToTarget -> {46 System.out.println("Attached to target");47 });48 devTools.addListener(Browser.detachedFromTarget(), detachedFromTarget -> {49 System.out.println("Detached from target");50 });51 devTools.addListener(Browser.targetCrashed(), targetCrashed -> {52 System.out.println("Target crashed");53 });54 devTools.addListener(Browser.targetChanged(), targetChanged -> {55 System.out.println("

Full Screen

Full Screen

createSession

Using AI Code Generation

copy

Full Screen

1DevTools devTools = createSession(new ChromeOptions());2DevTools devTools = createSession(new FirefoxOptions());3DevTools devTools = createSession(new EdgeOptions());4DevTools devTools = createSession(new SafariOptions());5DevTools devTools = createSession(new OperaOptions());6DevTools devTools = createSession(new InternetExplorerOptions());7DevTools devTools = createSession(new AndroidOptions());8DevTools devTools = createSession(new IOSOptions());9DevTools devTools = createSession(remoteWebDriver);10DesiredCapabilities capabilities = new DesiredCapabilities();11capabilities.setCapability(CapabilityType.BROWSER_NAME, "chrome");12DevTools devTools = createSession(remoteWebDriver);13DesiredCapabilities capabilities = new DesiredCapabilities();14capabilities.setCapability(CapabilityType.BROWSER_NAME, "chrome");15capabilities.setCapability(CapabilityType.PLATFORM_NAME, Platform.WIN10);16DevTools devTools = createSession(remoteWebDriver);17DesiredCapabilities capabilities = new DesiredCapabilities();18capabilities.setCapability(CapabilityType.BROWSER_NAME, "chrome");19capabilities.setCapability(CapabilityType.PLATFORM_NAME, Platform.WIN10);20capabilities.setCapability(CapabilityType.VERSION, "75");21DevTools devTools = createSession(remoteWebDriver);22DesiredCapabilities capabilities = new DesiredCapabilities();23capabilities.setCapability(CapabilityType.BROWSER_NAME, "chrome");24capabilities.setCapability(CapabilityType.PLATFORM_NAME, Platform.WIN10);25capabilities.setCapability(Capability

Full Screen

Full Screen

createSession

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.devtools.DevTools;2import org.openqa.selenium.devtools.v85.network.Network;3import org.openqa.selenium.devtools.v85.network.model.ConnectionType;4import org.openqa.selenium.devtools.v85.network.model.Request;5import org.openqa.selenium.devtools.v85.network.model.Response;6import org.openqa.selenium.devtools.v85.page.Page;7import org.openqa.selenium.devtools.v85.page.model.FrameId;8import org.openqa.selenium.devtools.v85.page.model.FrameResourceTree;9import org.openqa.selenium.devtools.v85.page.model.ResourceTreeFrame;10import org.openqa.selenium.devtools.v85.runtime.Runtime;11import org.openqa.selenium.devtools.v85.runtime.model.RemoteObject;12import java.util.List;13import static org.openqa.selenium.devtools.v85.network.Network.enable;14import static org.openqa.selenium.devtools.v85.network.Network.getResponseBody;15import static org.openqa.selenium.devtools.v85.network.Network.getResponseBodyForInterception;16import static org.openqa.selenium.devtools.v85.network.Network.interceptRequest;17import static org.openqa.selenium.devtools.v85.network.Network.interceptResponse;18import static org.openqa.selenium.devtools.v85.network.Network.setExtraHTTPHeaders;19import static org.openqa.selenium.devtools.v85.network.Network.setUserAgentOverride;20import static org.openqa.selenium.devtools.v85.network.Network.setCacheDisabled;21import static org.openqa.selenium.devtools.v85.network.Network.setBlockedURLs;22import static org.openqa.selenium.devtools.v85.network.Network.setBypassServiceWorker;23import static org.openqa.selenium.devtools.v85.network.Network.setConnectivity;24import static org.openqa.selenium.devtools.v85.network.Network.setCookies;25import static org.openqa.selenium.devtools.v85.network.Network.setCookie;26import static org.openqa.selenium.devtools.v85.network.Network.setOfflineMode;27import static org.openqa.selenium.devtools.v85.network.Network.setCacheDisabled;28import static org.openqa.selenium.devtools.v85.network.Network.setBlockedURLs;29import static org.openqa.selenium.devtools.v85.network.Network.setBypassServiceWorker;30import static org.openqa.selenium.devtools.v85.network.Network.setConnectivity;31import static org.openqa.selenium.devtools.v85.network.Network.setCookies;32import static org.openqa.selenium.devtools.v85.network.Network.setCookie;33import static org.openqa.selenium.devtools.v85.network.Network.setOfflineMode;34import static org.openqa.selenium.devtools.v85.network.Network.setCacheDisabled;35import static org.openqa.selenium.devtools.v85.network.Network.setBlockedURLs;36import

Full Screen

Full Screen

createSession

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.devtools.DevTools;3import org.openqa.selenium.devtools.v90.browser.Browser;4import org.openqa.selenium.remote.RemoteWebDriver;5import java.net.MalformedURLException;6import java.net.URL;7public class DevToolsTest {8 public static void main(String[] args) throws MalformedURLException {9 DevTools devTools = ((ChromeDriver) driver).getDevTools();10 devTools.createSession();11 devTools.send(Browser.getVersion());12 devTools.close();13 driver.close();14 }15}

Full Screen

Full Screen

createSession

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.devtools.DevTools2import org.openqa.selenium.devtools.v91.browser.Browser3import org.openqa.selenium.devtools.v91.browser.model.WindowState4def driver = new ChromeDriver()5def devTools = driver.getDevTools()6devTools.createSession()7devTools.send(Browser.setWindowBounds(WindowState.NORMAL))8import org.openqa.selenium.devtools.DevTools9import org.openqa.selenium.devtools.v91.browser.Browser10import org.openqa.selenium.devtools.v91.browser.model.WindowState11def driver = new ChromeDriver()12def devTools = driver.getDevTools()13def sessionId = devTools.createSession().getSessionId()14devTools = DevTools.create(driver, sessionId)15devTools.send(Browser.setWindowBounds(WindowState.NORMAL))16import org.openqa.selenium.remote.RemoteWebDriver17import org.openqa.selenium.chrome.ChromeOptions18import org.openqa.selenium.remote.DesiredCapabilities19def chromeOptions = new ChromeOptions()20def capabilities = DesiredCapabilities.chrome()21capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions)

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