How to maximize Chrome in Playwright using c# Nunit

1.9k Views Asked by At

Below code open Chrome in non maximised state. I can see the code online/youtube used in Java to change the screensize but not found anything for c#.

        public async Task Test1()
        {
            using var playwright = await Playwright.CreateAsync();
            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = false,
            });
            var context = await browser.NewContextAsync();
            // Open new page
            var page = await context.NewPageAsync();
            await page.GotoAsync("https://google.com/");
        }
3

There are 3 best solutions below

0
Christian Baumann On

To start the browser maximized, you need to pass null instead of width & height.

I don't have .NET installed, but it should be something like

await using
var context = await browser.NewContextAsync(new BrowserNewContextOptions {
    ViewportSize = new ViewportSize() null
});
0
Nick Graham On

I found that ViewportSize wouldn't accept null but passing in approximate values for a maximised screen got me the same result.

BrowserNewContextOptions browserNewContextOptions = new BrowserNewContextOptions();
browserNewContextOptions.ViewportSize = new ViewportSize { Height = 1000, Width = 1900 };
IBrowserContext Context = await browser.NewContextAsync(browserNewContextOptions);
2
I.sh. On

You need two things:

  1. Pass the --start-maximized flag to the Args of LaunchOptions
  2. Override the context-viewport default configuration with NoViewport
public async Task Test1()
{
    var launchOptions = new BrowserTypeLaunchOptions
    {
       Headless = false,
       Args = new List<string> { "--start-maximized" }
    };

    using var playwright = await Playwright.CreateAsync();
        
    await using var browser = await playwright.Chromium.LaunchAsync(launchOptions);

    var context = await browser.NewContextAsync(new BrowserNewContextOptions
    {
        ViewportSize = ViewportSize.NoViewport
    });

    var page = await context.NewPageAsync();

    await page.GotoAsync("https://google.com/");
}