package com.utopiadeals.framework; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.BrowserType; import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; public abstract class BrowserContextManager { protected Playwright playwright; private final boolean isHeadless; protected static final ThreadLocal contextThreadLocal = new ThreadLocal<>(); protected static final ThreadLocal pageThreadLocal = new ThreadLocal<>(); public BrowserContextManager(boolean isHeadless) { this.playwright = Playwright.create(); // Initialize Playwright here this.isHeadless = isHeadless; } public void initBrowserContext() { if (contextThreadLocal.get() == null) { BrowserContext browserContext = createBrowserContext(); contextThreadLocal.set(browserContext); pageThreadLocal.set(contextThreadLocal.get().newPage()); } } public abstract BrowserContext createBrowserContext(); public BrowserType.LaunchOptions getLaunchOptions() { BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions(); launchOptions.setHeadless(this.isHeadless); return launchOptions; } public static BrowserContext getBrowserContext() { return contextThreadLocal.get(); } public static Page getPage() { if (contextThreadLocal.get() == null) { throw new IllegalStateException("Browser context is not created."); } return pageThreadLocal.get(); // Creating and returning a new Page } public void closeBrowserContext() { if (contextThreadLocal.get() == null) { throw new IllegalStateException("Browser context is not created."); } contextThreadLocal.get().close(); contextThreadLocal.remove(); } public void closePlaywright() { playwright.close(); } }