Skip to main content
Transform your testing process with: Real Device Features, Company-wide Licences, & Test Observability

Learn about event-driven testing

Learn how to optimize your test scripts to use Selenium 4 event-driven testing with BrowserStack Automate.

Selenium 4 uses Chrome Debugging Protocol (CDP) to achieve event-driven testing with the help of the following features:

Note: CDP only supports chromium-based browsers, namely Chrome and Edge.

If you plan to perform event-driven tests, use the seleniumCdp capability in your test script.

Capability Description Expected values
seleniumCdp Enables the Selenium’s CDP features in a test script. Boolean.
Set to true if you plan to use CDP features. Accepted values are true and false. Default is false.
Note: Currently, all the feature implementation sample code snippets are available only in Java. We plan to add code snippets for other languages soon.

Listen to console.log events

Console logs are generally used to uncover the cause of a bug in the code execution. Use this API to listen to the console.log events and register callbacks to process the event for displaying the logs.

The following test script opens the Broken Images page and logs the console events to your IDE’s console :

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v94.log.Log;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";
  static Boolean success = false;

  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "chrome");
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "OS X");
    browserstackOptions.put("osVersion", "Big Sur");
    browserstackOptions.put("sessionName", "Console Logs");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);

      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();

      devTools.send(Log.enable());
      devTools.addListener(Log.entryAdded(),
          logEntry -> {
              System.out.println("text: " + logEntry.getText());
              System.out.println("level: " + logEntry.getLevel());
              success = true;
          });
      driver.get("https://the-internet.herokuapp.com/broken_images");
      Thread.sleep(1000 * 10);
      if (success) {
          markTestStatus("passed", "Console logs streaming", driver);
      } else {
          markTestStatus("failed", "Console logs did not stream", driver);
      }
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

Listen to JavaScript Exceptions

Exception, as commonly known, is an unusual event that breaks the normal execution flow of a program.

Use this API to listen to the JavaScript exceptions and register callbacks to process the exception details. These exception details can assist in further inspecting the cause and aiding the debugging process.

The following test script opens the Facebook Sign in page and clicks the Log In button without entering the required sign-in credentials. Thus, an exception is thrown and displayed on your IDE’s console.

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";
  static Boolean success = false;

  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "chrome");
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "OS X");
    browserstackOptions.put("osVersion", "Catalina");
    browserstackOptions.put("sessionName", "JS Exceptions");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);

      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();

      List<JavascriptException> jsExceptionsList = new ArrayList<>();
      Consumer<JavascriptException> addEntry = jsExceptionsList::add;
      devTools.getDomains().events().addJavascriptExceptionListener(addEntry);

      driver.get("https://facebook.com");

      WebElement link2click = driver.findElement(By.name("login"));
      ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);",
          link2click, "onclick", "throw new Error('My Error');");
      link2click.click();

      Thread.sleep(1000);
      for (JavascriptException jsException : jsExceptionsList) {
        System.out.println("JS exception message: " + jsException.getMessage());
        System.out.println("JS exception system information: " + jsException.getSystemInformation());
        jsException.printStackTrace();
        success = true;
      }
      Thread.sleep(1000);
      if (success) {
        markTestStatus("passed", "Js exception caught", driver);
      } else {
        markTestStatus("failed", "Js exception was not caught", driver);
      }
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

Intercept Network

Network events list the resources sent from the server to the browser. This helps in observing the performance of a web page by analyzing the type, size, name, and status of each individual element. However, you can mock the network response by intercepting the request.

Intercepting a network is applicable to scenarios where an end-to-end test is expected to run on a website that consists of a few non-existing pages, which are planned to be developed in the future.

Use this API to capture the network events of a website and intercept them as required.

The following test script performs network interception by mocking the response of the request sent to a non-existent web page:

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.function.Supplier;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.NetworkInterceptor;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.http.Route;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "edge");
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "OS X");
    browserstackOptions.put("osVersion", "Mojave");
    browserstackOptions.put("sessionName", "Network Interception");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);

      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();

      Supplier<InputStream> message = () -> new ByteArrayInputStream("Creamy, delicious cheese!".getBytes(StandardCharsets.UTF_8));

      NetworkInterceptor interceptor = new NetworkInterceptor(
          driver,
          Route.matching(req -> true)
          .to(() -> req -> new HttpResponse()
              .setStatus(200)
              .addHeader("Content-Type", StandardCharsets.UTF_8.toString())
              .setContent(message)));
      driver.get("https://example-sausages-site.com");
      String source = driver.getPageSource();
      System.out.println(source);

      if (source.contains("delicious cheese!")) {
        markTestStatus("passed", "Source contains the contents", driver);
      } else {
        markTestStatus("failed", "Content was not found in the source", driver);
      }
      interceptor.close();
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}


This test script passes when it encounters the mocked response on the non-existent web page.

Capture Performance Metrics

The performance metrics for a website are derived based on multiple factors, such as time to load, page speed, bounce rate, and so on. Using these metrics, you can take corrective measures to improve the overall experience for your users.

Use this API to capture performance metrics and fix any performance issues of a website.

The following test script opens BrowserStack and logs its performance metrics on your IDE’s console:

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v94.performance.Performance;
import org.openqa.selenium.devtools.v94.performance.model.Metric;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";

  static Boolean success = true;
  
  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "chrome");
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "Windows");
    browserstackOptions.put("osVersion", "8.1");
    browserstackOptions.put("sessionName", "Performance Metrics");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);

      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();

      devTools.send(Performance.enable(Optional.empty()));
      List<Metric> metricList = devTools.send(Performance.getMetrics());

      driver.get("https://browserstack.com");

      for(Metric m : metricList) {
        System.out.println(m.getName() + " = " + m.getValue());
        success = true;
      }
      if (success) {
        markTestStatus("passed", "Performance metrics fetched", driver);
      } else {
        markTestStatus("failed", "Performance metrics were not fetched", driver);
      }
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

Register Basic Auth

Some websites use the browser authentication method to secure some of their web pages. Using Selenium, you can write an automated test script that enters your credentials in the basic auth popup window whenever it appears.

The following test script opens a website and enters sample credentials in the basic auth popup window:

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
  
import org.openqa.selenium.By;
import org.openqa.selenium.HasAuthentication;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.UsernameAndPassword;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
  
public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "chrome");
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "OS X");
    browserstackOptions.put("osVersion", "Big Sur");
    browserstackOptions.put("sessionName", "Basic Auth");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);
  
      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();
  
      driver = augmenter.
          addDriverAugmentation("chrome", HasAuthentication.class, (caps, exec) -> (whenThisMatches, useTheseCredentials) -> devTools.getDomains().network().addAuthHandler(whenThisMatches, useTheseCredentials)).augment(driver);

      ((HasAuthentication) driver).register(UsernameAndPassword.of("foo", "bar"));
  
      driver.get("http://httpbin.org/basic-auth/foo/bar");
  
      String text = driver.findElement(By.tagName("body")).getText();
      System.out.println(text);
      if (text.contains("authenticated")) {
        markTestStatus("passed", "Authenticated", driver);
      } else {
        markTestStatus("failed", "Authentication failed", driver);
      }
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }
  
  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

Emulate Geolocation

Testing location-based scenarios are possibly emulating geolocation in the browser.

You might want to emulate geolocation to test some of the following scenarios:

  • For web applications dependent on knowing the user’s location to offer products or services relevant to the location.
  • Food delivery, mapping applications, and so on where the user’s location must be known to simulate other relevant features, such as arrival time, distance to cover, and so on.
  • Test to verify that location-specific parameters, such as currency, language, and so on, adapt correctly.

Use this API to simulate geo-location and perform an automated test.

The following test script sets the geolocation, visits the real-time location website, and then retrieves your machine’s live location:

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v94.emulation.Emulation;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "chrome");
    ChromeOptions options = new ChromeOptions();

    Map<String, Object> prefs = new HashMap<String, Object>();
    prefs.put("googlegeolocationaccess.enabled", true);
    prefs.put("profile.default_content_setting_values.geolocation", 1); // 1:allow 2:block
    prefs.put("profile.default_content_setting_values.notifications", 1);
    prefs.put("profile.managed_default_content_settings", 1);
    options.setExperimentalOption("prefs", prefs);
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);

    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "Windows");
    browserstackOptions.put("osVersion", "8");
    browserstackOptions.put("sessionName", "Emulate Geo Location");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);

      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();

      // setGeolocationOverride() takes lattitude, longitude, and accuracy as parameters.
      devTools.send(Emulation.setGeolocationOverride(Optional.of(19.1700841),
          Optional.of(72.8579897),
          Optional.of(1)));
      driver.get("https://my-location.org");

      String address = driver.findElement(By.id("address")).getText();
      System.out.println(address);
      if (address.contains("Mumbai")) {
        markTestStatus("passed", "Location is in Mumbai", driver);
      } else {
        markTestStatus("failed", "Location is not in Mumbai", driver);
      }
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

In the console of your IDE, based on where the machine is located, the location appears. You can change this test script to perform any other test case by simulating the location of your choice.

Emulate Network conditions

Websites are accessed over the internet with varying network speeds. Thus, it’s crucial to ensure a website works as expected under several network conditions. Using Selenium, you can write an automated test script to emulate network conditions for a website. The Network.emulateNetworkConditions function takes 5 parameters, namely offline, latency, downloadThroughput, uploadThroughput, and ConnectionType. You can set the ConnectionType can be BLUETOOTH, 2G, 3G, 4G, WIFI, ETHERNET, and NONE.

You might want to emulate geolocation to test some of the following scenarios:

  • Network performance when the same website is accessed by different connection types (networks)
  • Latency in the network for different network types.

Check out Parameters for Emulating Network Conditions to learn the available parameters and the format.

The following test script emulates the network speed of 420 Kbps, visits a speed calculator website, and then prints the internet speed:


import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Optional;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v93.network.Network;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "chrome");
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "Windows");
    browserstackOptions.put("osVersion", "7");
    browserstackOptions.put("sessionName", "Emulate Network");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);

      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();

      devTools.send(Network.emulateNetworkConditions(false, 0, 64 * 1024, 64 * 1024, Optional.empty()));
      driver.get("https://fast.com");
      Thread.sleep(15000);
      String speed = driver.findElement(By.id("speed-value")).getText();
      String units = driver.findElement(By.id("speed-units")).getText();
      System.out.println(speed);
      System.out.println(units);
      if (Float.parseFloat(speed) < 500 && units.equals("Kbps")) {
          markTestStatus("passed", "Speed is limited to 500 Kbps", driver);
      } else {
          markTestStatus("failed", "Speed is not limited to 500 Kbps", driver);
      }
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

This test script prints 420 Kbps in your IDE’s console. You can modify this test script to run a test case by simulating network conditions.

Override Device Mode to Set Dimensions

The layout of a website varies depending on the screen dimensions. Using Selenium’s integration with CDP, you can override the current device’s screen dimension and simulate a new dimension. This setting helps you perform automated tests on a website by simulating different screen dimensions.

The following test script overrides the default screen dimension, 1920x1080 with a new dimension and prints it:

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Optional;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v94.emulation.Emulation;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws MalformedURLException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("browserName", "chrome");
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "OS X");
    browserstackOptions.put("osVersion", "High Sierra");
    browserstackOptions.put("sessionName", "Override Device Mode");
    browserstackOptions.put("seleniumVersion", "4.0.0");
    browserstackOptions.put("seleniumCdp", true);
    capabilities.setCapability("bstack:options", browserstackOptions);

    WebDriver driver = new RemoteWebDriver(new URL(REMOTE_URL), capabilities);

    try {
      Augmenter augmenter = new Augmenter();
      driver = augmenter.augment(driver);

      DevTools devTools = ((HasDevTools) driver).getDevTools();
      devTools.createSession();

      devTools.send(Emulation.setDeviceMetricsOverride(375,
          812,
          50,
          true,
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty()));
      driver.get("http://whatismyscreenresolution.net/");
      String resolution = driver.findElement(By.id("resolution")).getText();

      System.out.println(resolution);
      if (resolution.equals("375x812")) {
        markTestStatus("passed", "Screen resolution is 375x812", driver);
      } else {
        markTestStatus("failed", "Screen resolution is not 375x812", driver);
      }
      driver.quit();

    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback!

Talk to an Expert
Download Copy