BrowserContext in Playwright

 

In Playwright, a BrowserContext is like a separate browser session within a single browser instance. Think of it as creating multiple independent browser profiles, each with its own cookies, cache, local storage, etc.

















Why BrowserContext is Useful:

  • Isolates tests from each other (test parallelism without shared cookies/storage).

  • Simulates different users in the same browser instance.

  • Avoids opening multiple browser windows (faster and more memory efficient).




Important Points:


FeatureDescription
IsolationEach context has its own cookies, local storage, and session data.
Multiple tabsYou can open multiple pages (tabs) inside one context.
Faster than launching new browserYou don’t need to open a new browser each time, just create a new context.


Java Example with Playwright

Let's create two BrowserContext objects to simulate two users logging in separately.


Maven Dependencies:


<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.43.0</version> <!-- use latest -->
</dependency>




Java Code: BrowserContext Example


import com.microsoft.playwright.*;

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

            // Create first context (User A)
            BrowserContext userAContext = browser.newContext();
            Page userAPage = userAContext.newPage();
            userAPage.navigate("https://example.com");
            System.out.println("User A title: " + userAPage.title());

            // Create second context (User B)
            BrowserContext userBContext = browser.newContext();
            Page userBPage = userBContext.newPage();
            userBPage.navigate("https://example.com");
            System.out.println("User B title: " + userBPage.title());

            // Perform user-specific actions
            // Example: log in as two different users, store cookies separately

            // Cleanup
            userAContext.close();
            userBContext.close();
            browser.close();
        }
    }
}


Use Case Example

In test automation:

  • You can simulate User A logs in and books a ticket, while User B cancels it.

  • Run in the same test thread efficiently using isolated sessions.

No comments:

Post a Comment