Maximize Window in Playwright

In Playwright, maximizing the browser window means opening the browser in such a way that it occupies the full available screen space of the operating system, similar to when a user clicks the maximize button on a normal browser window.

By default, when Playwright launches a browser, it opens in a standard viewport size (often 1280×720 or as configured). If the viewport is not specified, Playwright automatically applies its default dimensions. However, maximizing is not automatically done because Playwright is designed to provide predictable, controlled environments for automation rather than adapting to the current screen resolution.

(a) Maximizing the window is useful in scenarios such as:

(b) When testing applications that behave differently on full-screen layouts versus smaller viewports.

(c) When elements shift position or appear only in larger layouts (e.g., responsive designs).

(d) When ensuring that the UI is tested under real-world screen conditions, such as a user running the browser maximized.

Although there isn’t a direct "maximize" command in Playwright like in Selenium, the effect is usually achieved by setting the browser window size equal to the screen’s resolution. In essence, maximizing is about resizing the Playwright browser context to cover the full display area so that the tests replicate what an end user would see on a maximized browser.

In order to maximize window while using Playwright Java, you typically set the viewport size to match the screen size, since Playwright does not have a direct method like maximize() (as in Selenium). However, we can simulate maximization by:

  • Launching the browser in headful mode.
  • Fetching the screen dimensions.
  • Setting the viewport to full screen dimensions.
















Steps to Maximize Browser Window in Playwright Java:

  • Launch Playwright.
  • Start browser in headful mode (not headless).
  • Use setViewportSize() to simulate maximized window.














Java Code Example to Maximize Window in Playwright


import com.microsoft.playwright.*;

public class MaximizeWindowExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            // Launch the browser in headful mode (so we can see the window)
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Create a new browser context without a specified viewport size (will use system default)
            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setViewportSize(null));

            // Create a new page
            Page page = context.newPage();

            // Navigate to a website
            page.navigate("https://example.com");

            // Optional: log current viewport size
            System.out.println("Viewport size: " + page.viewportSize());

            // Wait to see the maximized window
            page.waitForTimeout(5000); // 5 seconds

            // Close browser
            browser.close();
        }
    }
}


Explanation:

  • .setHeadless(false): Launches the browser in visible mode.

  • .setViewportSize(null): Instructs Playwright to use the full available screen size, which mimics maximizing.
  • page.waitForTimeout(5000): Allows you to see the effect before closing the browser.



Below is the difference between headed mode and headless mode

Headed Mode (UI Visible)

  • In this mode, the browser actually opens on your screen.
  • If you want a maximized effect, you need to set the window size equal to the system’s screen resolution (e.g., 1920×1080).
  • Since the browser is visible, you can truly replicate what happens when a real user clicks the maximize button.
  • This is often used for manual debugging, visual checks, or when testing UI behavior at full resolution.

Headless Mode (UI Hidden)

  • In headless mode, there’s no actual "window" being drawn on the screen.
  • The concept of "maximization" doesn’t really exist, since nothing is visible.
  • Instead, Playwright just renders pages in whatever viewport size you specify.
  • If you want the same conditions as a maximized window, you simply configure the viewport to match a full HD resolution (e.g., 1920×1080).

Suggested Posts:

1. Handle Alerts in Playwright
2. BrowserContext in Playwright
3. Playwright with JUnit
4. Handle IFrames in Playwright
5. Page Object Model in Playwright

BrowserContext in Playwright

 

In Playwright, a BrowserContext is like an isolated, independent session within a browser. We can think of it as a separate browser profile that does not share cookies, cache, or storage with other contexts, even though they run within the same browser instance. 

This makes it very useful for testing scenarios where you want multiple users to interact with the same application without interfering with each other—for example, logging in as two different users simultaneously. 

Each context can have its own set of pages (tabs) and can be configured with settings such as viewport size, geolocation, user agent, or permissions. Unlike launching multiple browsers, creating multiple contexts is lightweight and much faster, because contexts share the same underlying browser process but remain completely isolated. 

This improves performance, reduces resource usage, and allows for parallel test execution. In short, BrowserContext enables efficient, scalable, and realistic testing by simulating multiple independent browser environments within a single browser instance.

















Why BrowserContext is useful in Playwright:

1. Test Isolation

  • Each BrowserContext has its own cookies, cache, and local storage.

  • This means multiple tests can run in parallel without sharing session data.
  • Example: One context can simulate a logged-in user, while another can simulate a guest user.

2. Faster Execution
  • Instead of launching a full new browser instance for every test, you can just create a new BrowserContext.
  • This is much faster and lighter on resources.

3. Multi-User Scenarios

  • You can easily test scenarios involving multiple users at the same time. Below is the example.
        Context A = Seller account
        Context B = Buyer account
        Both interact with the same application in parallel, just like in real life.


4. Parallel Testing
  • Multiple contexts allow parallel execution inside a single browser.
  • This speeds up test suites significantly.

5. Clean-up Simplicity
  • When you close a BrowserContext, all related data (cookies, storage, sessions) is automatically cleared.
  • This prevents data leakage between tests.


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








(a) In above code, we are creating two BrowserContexts by using code:
BrowserContext userAContext = browser.newContext();

(b) Once we create BrowserContext object, we are creating Page object by:
Page userAPage = userAContext.newPage();

(c) Then, we are launching browser by using navigate()
userAPage.navigate("https://example.com");

(d) Then, we are printing web page title by title()
System.out.println("User A title: " + userAPage.title());


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();
        }
    }
}


Below are some use case example

In test automation:

  • We 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.


Suggested Posts:

1. Handle Alerts in Playwright
2. Handle Shadowdom in Playwright
3. Handle Dropdowns in Playwright
4. Handle IFrames in Playwright
5. Thread Local in Playwright

Disclaimer

 

Disclaimer – Tutorials123.com

The information provided on Tutorials123.com is for educational and informational purposes only. While we make every effort to ensure the accuracy and reliability of the information presented, we make no guarantees of any kind regarding the completeness, accuracy, reliability, suitability, or availability of any content on this website.


Use at Your Own Risk

Any action you take based on the information found on Tutorials123.com is strictly at your own risk. We will not be liable for any losses or damages — direct or indirect — in connection with the use of our website.


External Links

Our website may contain links to external websites. We do not have control over the content or nature of those sites and are not responsible for any damages or losses caused by visiting them. The inclusion of external links does not imply a recommendation or endorsement of the views expressed within them.


Technical & Code Tutorials

All programming tutorials, scripts, and code samples are provided "as is" without warranty of any kind. Always test any code in a safe environment before using it in a live project.


Advertisements

Advertisements appearing on Tutorials123.com may be provided by third-party ad networks such as Google AdSense. These companies may use cookies to serve ads based on your interests. For details, please refer to our Privacy Policy.


Consent

By using our website, you hereby consent to our disclaimer and agree to its terms.


Updates

We may update this disclaimer from time to time. Any changes will be posted on this page.

Advertise with us

 

Advertise With Us – Tutorials123.com

Looking to promote your brand, product, or service to a tech-savvy and engaged audience? tutorials123.com offers effective advertising opportunities to help you reach your target customers.


Why Advertise With Us?

  • Targeted Audience – Our visitors are students, professionals, and tech enthusiasts interested in programming, web development, and technology tutorials.

  • High Engagement – Readers actively interact with our content and trust our recommendations.

  • Global Reach – We attract traffic from multiple countries, ensuring your brand gets maximum visibility.


Advertising Options

We offer a variety of ad placements and promotional opportunities:

  • Banner Ads (Header, Sidebar, Footer)

  • Sponsored Articles / Guest Posts

  • Product Reviews & Recommendations

  • Text Link Ads

  • Custom Campaigns (tailored to your needs)


Get in Touch

To discuss advertising opportunities, rates, and availability, please contact us at:

himanshupal4u@gmail.com
Website: https://www.tutorials123.com

About us

 

About Us – Tutorials123.com


Welcome to Tutorials123.com – your go-to destination for clear, practical, and easy-to-understand tutorials.


We believe learning should be simple, accessible, and enjoyable. Our mission is to provide step-by-step guides, coding tips, technology updates, and helpful resources for learners, professionals, and enthusiasts from all walks of life.


At Tutorials123.com, you will find:

  • Programming Tutorials – Covering software automation testing tools like Selenium, TestNG, Cucumber, Rest Assured, and more.

  • Tech How-To Guides – From software setup to troubleshooting tips.

  • Career & Learning Resources – Helping you grow your skills and knowledge.


Our Vision

To make quality learning resources available to everyone, free of unnecessary complexity, and accessible anywhere in the world.


Our Values

  • Clarity – We simplify complex topics.

  • Quality – We ensure accuracy and up-to-date content.

  • Community – We value feedback and encourage knowledge sharing.


Whether you’re a studentself-learner, or professional, our aim is to help you understand and apply technology in the most effective way.


Contact Us: himanshupal4u@gmail.com
Website: https://www.tutorials123.com


Privacy Policy

 

Privacy Policy for tutorials123.com

At tutorials123.com, we value your privacy and are committed to protecting your personal information. This Privacy Policy outlines how we collect, use, and safeguard your information when you visit our website.


1. Information We Collect

When you visit Tutorials123.com, we may collect:

  • Personal Information (only if you voluntarily provide it via contact forms, comments, or subscription, such as your name and email address).

  • Non-Personal Information such as browser type, IP address, pages visited, and time spent on the site (collected automatically via analytics tools).



2. How We Use Your Information

We may use the collected information to:

  • Improve website content and user experience.

  • Respond to inquiries and comments.

  • Send newsletters (only if you have subscribed).

  • Display relevant ads through advertising networks like Google AdSense.



3. Cookies and Third-Party Services

  • Tutorials123.com uses cookies to improve user experience.

  • Third-party vendors, including Google, use cookies (such as the DoubleClick DART cookie) to serve ads based on users’ prior visits.

  • You may opt out of personalized Google ads by visiting: Google Ads Settings.



4. Third-Party Links

Our site may contain links to other websites. We are not responsible for the privacy practices or content of those sites.



5. Google AdSense & Analytics

  • We use Google AdSense for displaying ads. Google may use cookies to serve personalized ads.

  • We use Google Analytics to understand how visitors interact with our site.

For more information on how Google collects and uses data, please visit:
Google Privacy Policy



6. Your Data Protection Rights

You have the right to:

  • Access, update, or delete your personal information.

  • Opt out of cookies through your browser settings.



7. Updates to This Policy

We may update this Privacy Policy from time to time. The updated version will be posted on this page with the revision date.

Contact us