How to Handle Browser Contexts and Sessions in Playwright Java

Playwright Java browser contexts diagram showing multiple isolated contexts under one browser instance

When working with Playwright Java browser contexts, you can easily create isolated environments within a single browser instance. Each browser context behaves like a separate browser profile, allowing you to open multiple independent sessions in Playwright without interference. This makes it ideal for testing scenarios where different users, roles, or sessions need to run simultaneously.

Browser contexts are especially useful for managing cookies, local storage, and authentication states independently. They help you achieve faster, more reliable tests by avoiding the overhead of launching a new browser for every test case.

In this tutorial, you will learn how to use Playwright Java’s newContext() to create and manage separate browser sessions, handle multiple browser sessions efficiently, and maintain user login states across tests for better performance and scalability.

Diagram explaining Playwright Java browser contexts and isolated sessions
Visual representation of multiple browser contexts running independently in Playwright Java

What are Browser Contexts in Playwright Java?

A browser context in Playwright Java is an isolated environment inside a single browser instance. Each context maintains its own cookies, cache, and session storage, just like a separate browser profile. This means you can create multiple independent browser contexts that do not share login information, site data, or storage state with each other.

Example showing isolated browser contexts in Playwright Java
Each browser context behaves like a separate browser profile in Playwright Java

Behind the scenes, Playwright runs one browser process that can hold several lightweight contexts. Each context acts as a sandbox, making it perfect for testing different user roles or running parallel sessions without any data overlap.

Think of a browser context as a separate browser window with its own session, while the main browser instance acts as the engine powering all of them. This isolation helps automate scenarios like multi-user testing, secure login handling, and data-driven workflows efficiently.

Here’s a simple Java example that shows how to create a new browser context:

package com.example.test;

import com.microsoft.playwright.*;

public class BrowserContextExample {
	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

			// Create a new isolated browser context
			BrowserContext context = browser.newContext();

			// Open a new page within this context
			Page page = context.newPage();
			page.navigate("https://example.com");

			// Close context after use
			context.close();
		}
	}
}

In this example, the newContext() method creates an independent session that does not share cookies or storage with other contexts. This approach is key to managing isolated browser sessions efficiently in Playwright Java.

Playwright Java newContext(): Creating Independent Sessions

The newContext() method in Playwright Java is used to create new, isolated browser sessions within the same browser instance. Each context operates independently, meaning it does not share cookies, cache, local storage, or session data with any other context. This makes it extremely useful for testing scenarios where multiple users or sessions need to interact with the same web application simultaneously.

For example, if you want to test how two users (like an admin and a customer) interact on the same site, you can use separate browser contexts. Both can be active at the same time without interfering with each other’s data or login sessions.

Here’s a Java example that demonstrates creating and using multiple contexts in one test:

package com.example.test;

import com.microsoft.playwright.*;

public class MultipleContextsExample {
	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

			// Create first independent browser context
			BrowserContext adminContext = browser.newContext();
			Page adminPage = adminContext.newPage();
			adminPage.navigate("site url/admin-login");
			// Write admin login steps.

			// Create second independent browser context
			BrowserContext userContext = browser.newContext();
			Page userPage = userContext.newPage();
			userPage.navigate("site url/user-login");
			// Write user login steps.

			// Both sessions are isolated from each other
			System.out.println("Admin and user logged in independently in separate contexts.");

			// Close contexts after use
			adminContext.close();
			userContext.close();
		}
	}
}

In this example, the admin and user sessions run in two completely separate browser contexts. They do not share cookies, authentication state, or cache, ensuring accurate and isolated test results. Using Playwright Java newContext() like this helps you simulate real-world multi-user scenarios efficiently.

Running Multiple Browser Sessions in Playwright Java

The ability to run multiple browser sessions is one of the most powerful features of Playwright Java. It allows testers to simulate different users, roles, or environments at the same time within a single test execution. Each session operates in its own browser context, ensuring that cookies, local storage, and authentication data remain completely isolated.

For example, imagine testing an e-commerce site where an admin manages products while a customer browses and places orders. With Playwright Java, you can open two independent sessions using different contexts to test both roles simultaneously without any conflict.

Running multiple sessions in parallel not only saves time but also improves test coverage by validating real-world user interactions across different roles. However, it is important to manage system resources efficiently. Avoid creating unnecessary contexts, close each context after execution, and reuse browser instances whenever possible for better performance.

Here is a sample Java code demonstrating how to run multiple browser sessions in one test:

package com.example.test;

import com.microsoft.playwright.*;

public class MultipleSessionsExample {
	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			// Launch a single browser instance
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

			// Create first context for Admin user
			BrowserContext adminContext = browser.newContext();
			Page adminPage = adminContext.newPage();
			adminPage.navigate("site url/admin");
			adminPage.fill("#username", "admin_user");
			adminPage.fill("#password", "admin_pass");
			adminPage.click("#loginButton");

			// Create second context for Customer user
			BrowserContext customerContext = browser.newContext();
			Page customerPage = customerContext.newPage();
			customerPage.navigate("site url/login");
			customerPage.fill("#username", "customer_user");
			customerPage.fill("#password", "customer_pass");
			customerPage.click("#loginButton");

			// Both sessions are isolated and can be tested simultaneously
			System.out.println("Admin and Customer logged in separately in independent browser sessions.");

			// Perform test actions for both roles
			adminPage.click("#addProduct");
			customerPage.click("#viewProducts");

			// Best practice: close contexts after test
			adminContext.close();
			customerContext.close();
		}
	}
}

In this example, both the admin and customer sessions run independently in separate contexts using the same browser instance. Each context has its own cookies, cache, and login state, ensuring clean and reliable test execution.

By following best practices such as reusing the same browser instance and closing contexts after use, you can achieve faster execution, lower resource usage, and more dependable Playwright Java multiple browser sessions testing.

Playwright Java newContext() with Options

The newContext() method in Playwright Java is not limited to creating blank browser sessions. It also allows you to configure different settings such as viewport size, user agent, locale, time zone, and even device emulation. These options help you create realistic test environments that match your target users’ devices and regions.

By passing configuration options to newContext(), you can simulate various browser conditions without needing multiple browser installations. For example, you can test how your application behaves in different screen sizes or languages by simply adjusting context options.

Here is a Java example showing how to use newContext() with options:

package com.example.test;
import com.microsoft.playwright.*;

public class ContextWithOptionsExample {
	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

			// Create a new browser context with custom options
			Browser.NewContextOptions contextOptions = new Browser.NewContextOptions().setViewportSize(1280, 720)
					.setLocale("en-GB").setUserAgent("CustomUserAgent/1.0").setTimezoneId("Europe/London");

			BrowserContext context = browser.newContext(contextOptions);

			// Open a new page with the configured settings
			Page page = context.newPage();
			page.navigate("site url");

			System.out.println("Browser context launched with custom options.");

			context.close();
		}
	}
}

In this example, the test runs with a specific viewport size, locale, time zone, and user agent, all controlled through newContext(). This flexibility makes it easy to simulate various devices and regional settings in your tests.

When you create a new browser context in Playwright, it automatically acts like incognito mode in regular browsers. Each context is isolated from others, with no shared cookies or storage data. This ensures clean and repeatable tests every time you run your automation suite.

Managing User Login State and Cookies

One of the most practical features in Playwright Java is the ability to save and reuse session login state across tests. This helps you avoid performing repetitive login steps in every test case, which saves time and reduces flakiness. Once a user logs in successfully, you can capture the session data, store it in a file, and then reuse it in future tests.

Every browser context in Playwright Java maintains its own set of cookies, local storage, and session data. These cookies can be saved and restored later, allowing your tests to start in an already authenticated state. This approach is particularly useful when dealing with large test suites that require multiple authenticated test cases.

Here’s an example showing how to save the session login state after a successful login:

package com.example.test;

import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class SaveLoginStateExample {
	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
			BrowserContext context = browser.newContext();
			Page page = context.newPage();

			// Perform login steps
			page.navigate("site url/login.html");
			page.fill("#username", "testuser");
			page.fill("#password", "test123");
			page.locator("button:has-text('Login')").click();

			// Wait for successful login
			page.waitForURL("site url/dashboard.html");

			// Save the storage state to a JSON file
			context.storageState(new BrowserContext.StorageStateOptions().setPath(Paths.get("loginState.json")));

			System.out.println("Login session saved successfully.");
			context.close();
		}
	}
}

Once the session state is saved, you can load it in another test to reuse the logged-in session without repeating the login process:

package com.example.test;

import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class ReuseLoginStateExample {
	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

			// Load previously saved login state
			Browser.NewContextOptions options = new Browser.NewContextOptions()
					.setStorageStatePath(Paths.get("loginState.json"));
			BrowserContext context = browser.newContext(options);

			Page page = context.newPage();
			page.navigate("site url/dashboard.html");

			System.out.println("Logged in using saved session state.");
			context.close();
		}
	}
}

If you ever need to start fresh, you can simply skip loading the stored state or create a new context without passing the session file. This will give you a clean slate with no cookies or local storage.

By saving and restoring browser context cookies and session data, you can build faster and more efficient test suites while maintaining complete control over authentication and session handling in Playwright Java.

Here’s the corrected, SEO-friendly version of that section with thread-safe guidance and updated example:

Playwright Java Parallel Tests Using Contexts

Playwright Java browser contexts make it easy to run multiple isolated sessions in parallel. Each context works like a separate browser profile, maintaining its own cookies, cache, and session data. This feature is especially useful when you need to test multiple users or roles (such as administrators and customers) simultaneously.

Playwright Java parallel test execution using multiple browser contexts
Running isolated sessions in parallel using Playwright Java contexts

However, in Playwright Java, the Playwright and Browser Objects are not thread-safe. To run tests in true parallel mode, each test or thread must create its own Playwright and Browser instance. This ensures no channel conflicts or errors occur during concurrent execution.

Below is a TestNG example showing how to run Playwright Java tests in parallel safely using independent browser contexts:

package com.example.test;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;

import org.testng.annotations.*;

public class ParallelContextTests {
	@Test(threadPoolSize = 2, invocationCount = 2)
	public void testParallelLoginSessions() {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
			BrowserContext context = browser.newContext();

			Page page = context.newPage();
			page.navigate("file:///D:/session/login.html");

			page.locator("#username").fill("user" + Thread.currentThread().getId());
			page.locator("#password").fill("password123");
			page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Login")).click();

			page.waitForSelector("h2");
			System.out.println("Logged in successfully for thread: " + Thread.currentThread().getId());

			context.close();
			browser.close();
		}
	}
}

Performance Tips for Parallel Execution

  • Create isolated instances: Each parallel test should create its own Playwright and Browser instances to avoid thread conflicts.
  • Use headless mode: This reduces resource consumption and speeds up execution.
  • Keep test data unique: Assign different usernames or input data for each thread to prevent overlap.
  • Close contexts properly: Always close the context and browser after each test to release memory.

By following these best practices, you can safely run Playwright Java parallel tests using multiple browser contexts, ensuring fast, stable, and isolated automation sessions.

Difference Between Browser Context and Page

In Playwright Java, understanding the difference between a browser context and a page is essential for writing efficient tests.

Think of it this way:

  • A browser context is like opening a completely separate browser window with its own session, cookies, and cache.
  • A page is like opening a tab inside that window.

You can have multiple pages (tabs) inside one browser context, and multiple contexts can run independently without sharing data between them.

Here’s a short example showing how to create multiple pages within a single context:

package com.example.test;

import com.microsoft.playwright.*;

public class ContextVsPageExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      BrowserContext context = browser.newContext(); // one browser context

      // multiple pages (tabs) within the same context
      Page page1 = context.newPage();
      page1.navigate("https://playwright.dev/java/");

      Page page2 = context.newPage();
      page2.navigate("https://playwright.dev/python/");

      System.out.println("Two pages opened in one browser context.");

      context.close();
      browser.close();
    }
  }
}

Each page can run its own actions, but since they share the same browser context, they also share cookies and login sessions. If you need total isolation between users, create a new browser context instead of just a new page.

Handling Multiple Tabs in Playwright Java

In Playwright Java, multiple tabs are managed using page objects within the same browser context. Each tab is represented by a Page instance, and you can easily switch between them when a new one opens. This is useful for testing scenarios like links that open in a new tab or pop-ups that appear after a button click.

Here’s an example where clicking a button opens a new tab, and the test switches to it:

import com.microsoft.playwright.*;

public class HandleMultipleTabsExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
      BrowserContext context = browser.newContext();
      Page page = context.newPage();

      page.navigate("site url/login.html");

      // Click button that opens a new tab
      page.locator("#openNewTabButton").click();

      // Wait for the new tab to open
      Page newTab = context.waitForPage(() -> {
        // Trigger that opens the new tab
        page.locator("#openNewTabButton").click();
      });

      // Switch to the new tab and perform actions
      newTab.waitForLoadState();
      System.out.println("New tab URL: " + newTab.url());

      // Close the new tab
      newTab.close();

      // Continue working on the original tab
      page.bringToFront();
      System.out.println("Back to the original tab.");

      context.close();
      browser.close();
    }
  }
}

Best Practices for Handling Multiple Tabs

  • Use waitForPage() when expecting a new tab to open, ensure synchronization between actions and page events.
  • Close unused tabs to save resources and maintain test stability.
  • Reuse existing tabs whenever possible if your scenario allows it.
  • Keep track of all Page objects created within a context for better control during cleanup.

By using browser contexts and page objects together, you can efficiently handle multiple tabs in Playwright Java while keeping your tests clean and well-structured.

Conclusion

Playwright Java browser contexts make it easy to manage multiple users, isolated sessions, and cleaner test environments. By creating independent contexts, you can test various roles, login states, or configurations without interference between sessions.

Using the newContext() method allows you to run more organized and reliable tests while maintaining full control over cookies, cache, and storage data. It also helps simulate real-world user behavior by creating truly isolated browser instances.

When combined with features like saved sessions, multiple pages, and parallel execution, Playwright Java offers faster, more scalable, and maintainable test automation for modern web applications.

author avatar
Aravind QA Automation Engineer & Technical Blogger
Aravind is a QA Automation Engineer and technical blogger specializing in Playwright, Selenium, and AI in software testing. He shares practical tutorials to help QA professionals improve their automation skills.
Stay Updated with New Articles
Get the latest tutorials and insights delivered to your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *