How to launch Playwright in browserstack and locally with Java?

Sameera De Silva
3 min readJul 14, 2023

--

For that you don’t need any browserstack dependencies. we only need below dependency.

        <dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.33.0</version>
</dependency>

The full code with Browerstack is as per below.

package com.sam.scripts;

import com.google.gson.JsonObject;
import com.microsoft.playwright.*;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class LaunchBrowserInBrowserStack {

final String BROWSERSTACK_USERNAME = "myusername";
final String BROWSERSTACK_ACCESS_KEY = "myaccesskey";
Playwright playwright;
Browser browser;

@BeforeClass
public void setUp() throws UnsupportedEncodingException {


JsonObject capabilitiesObject = new JsonObject();
capabilitiesObject.addProperty("browser", "chrome");
capabilitiesObject.addProperty("browser_version", "latest");
capabilitiesObject.addProperty("os", "windows");
capabilitiesObject.addProperty("os_version", "10");
capabilitiesObject.addProperty("name", "Playwright in browserstack");
capabilitiesObject.addProperty("build", "playwright-java-5");
capabilitiesObject.addProperty("project", "APP Automation Project"); //This will create a project in BrowserStack UI, so easy to organize.
capabilitiesObject.addProperty("browserstack.username", BROWSERSTACK_USERNAME);
capabilitiesObject.addProperty("browserstack.accessKey", BROWSERSTACK_ACCESS_KEY);

playwright = Playwright.create();
BrowserType chromium = playwright.chromium();
String caps = URLEncoder.encode(capabilitiesObject.toString(), "utf-8");
String ws_endpoint = "wss://cdp.browserstack.com/playwright?caps=" + caps;
browser = chromium.connect(ws_endpoint);

}

@Test
public void firstTest() {
Page page = browser.newPage();
page.navigate("https://the-internet.herokuapp.com/");
System.out.println(page.title());
// Wait for the element to be available Wait are optional.
page.waitForSelector("//a[contains(@href, '/hovers')]");
// Click the element
page.click("//a[contains(@href, '/hovers')]");
Locator myImage = page.locator("(//img[@alt='User Avatar'])[1]");
myImage.hover();
// Wait for the element with the text to be available
page.waitForSelector("h5");
// Retrieve the text of the element
String elementText = page.innerText("h5");
System.out.println("Text after hover: " + elementText);
page.close(); //Closes the current page.
browser.close();// Closes all pages in the current browser context.
//Closes the Playwright instance. It terminates the Playwright browser automation tool, including all browsers, pages, and contexts created using Playwright.
playwright.close();
}
}

Further readings-https://github.com/browserstack/playwright-browserstack/blob/main/playwright-java/src/test/java/com/browserstack/PlaywrightSessionDetailsTest.java

If you don’t want to run without BrowserStack and just want to execute locally, use the below code.

package com.sam.scripts;

import com.microsoft.playwright.*;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;


public class LaunchBrowser {
// https://www.youtube.com/watch?v=CvS8KK6XQHk&list=PLZMWkkQEwOPliOm7TkV0Ndg45cJPDthDC&index=2&ab_channel=LambdaTest
@BeforeClass
public void setUp() {
System.out.println("Hello TestNG");
}

@Test
public void firstTest() {
/* This line creates a new instance of the Playwright framework, which is used for automating web browsers.
It does not create a singleton instance of the Playwright framework.
Each time this line is executed, a new instance of the Playwright object is created.
*/
Playwright playwright = Playwright.create();
/*
This code initializes a new Chromium browser instance using Playwright's Chromium-specific implementation.
By default, it's headless. So to avoid it setHeadless(false)
So it launches the browser in non-headless mode, which means the browser window will be visible during the test execution.
If setHeadless(true) were used, the browser would run in the background without a visible window.
*/
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

// This line creates a new page object within the browser instance. The page object represents a single web page that can be navigated, interacted with, and tested.(It's kind of tab but exactly a tab.)
Page page = browser.newPage();
// This code instructs the page object to navigate to the specified URL
page.navigate("https://the-internet.herokuapp.com/");
System.out.println(page.title());
assertThat(page).hasTitle("The Internet");
// Wait for the element to be available Wait are optional.
page.waitForSelector("//a[contains(@href, '/hovers')]");
// Click the element
page.click("//a[contains(@href, '/hovers')]");

Locator myImage = page.locator("(//img[@alt='User Avatar'])[1]");
myImage.hover();
// Wait for the element with the text to be available
page.waitForSelector("h5");
// Retrieve the text of the element
String elementText = page.innerText("h5");
System.out.println("Text after hover: " + elementText);
// Closes the currently open web page or browsing context. Terminates any ongoing network activity related to the page.
page.close();
// Closes the browser window(s) associated with the browser instance.
browser.close();
// playwright.close() command is used to close the page that is currently open in the Chromium browse
playwright.close();
}
}

To launch Firefox in BrowserStack use the below code

This will run on Nightly browser.

Reason-

“Playwright uses its own Firefox build. That build is based on the Firefox Nightly build. That’s why you are getting that browser. You won’t be able to use the stock browser version.”

    @BeforeClass
public void setUp() throws UnsupportedEncodingException {

JsonObject capabilitiesObject = new JsonObject();
capabilitiesObject.addProperty("browser", "playwright-firefox"); // specify firefox browser
capabilitiesObject.addProperty("browser_version", "latest");
capabilitiesObject.addProperty("os", "windows");
capabilitiesObject.addProperty("os_version", "10");
capabilitiesObject.addProperty("project", "APP Automation Project"); // optional, create a project in BrowserStack UI
capabilitiesObject.addProperty("name", "Playwright in browserstack");
capabilitiesObject.addProperty("build", "App automation playwright build");
capabilitiesObject.addProperty("browserstack.username", "my username");
capabilitiesObject.addProperty("browserstack.accessKey", "my password");

playwright = Playwright.create();
BrowserType firefox = playwright.firefox(); // use firefox browser type
String caps = URLEncoder.encode(capabilitiesObject.toString(), "utf-8");
String ws_endpoint = "wss://cdp.browserstack.com/playwright?caps=" + caps;
browser = firefox.connect(ws_endpoint);

}

Further references-

More capabilities

// BrowserStack Specific Capabilities.
const caps = {
os: 'osx',
os_version: 'catalina',
browser: 'chrome',
browser_version: 'latest',
'browserstack.geoLocation': 'FR',
project: 'My First Project',
build: 'playwright-build-1',
name: 'My first playwright test',
buildTag: 'reg',
resolution: '1280x1024',
'browserstack.local': 'true',
'browserstack.localIdentifier': 'local_connection_name',
'browserstack.playwrightVersion': '1.latest',
'client.playwrightVersion': '1.latest',
'browserstack.debug': 'true', // enabling visual logs
'browserstack.console': 'info' // Enabling Console logs for the test
'browserstack.networkLogs': 'true' // Enabling network logs for the test
'browserstack.interactiveDebugging': 'true',
}

--

--

No responses yet