Distributing applications that depend on Microsoft.Playwright

 
 
  • Gérald Barré

To use Playwright, you need to install the NuGet package and the browsers. The documentation tells us to use the following command to install the browsers:

Shell
# Create project
dotnet new console -n PlaywrightDemo
cd PlaywrightDemo

# Install dependencies, build project and download necessary browsers.
dotnet add package Microsoft.Playwright
dotnet build

dotnet tool install --global Microsoft.Playwright.CLI
playwright install

This works fine on the developer machine. However, the command line playwright install must run in the project directory as it requires a csproj file. Also, as this is a dotnet tool, you need to install the .NET SDK. This is clearly a show stopper when you are trying to publish the application. Indeed, no one would like to add the .NET SDK as a dependency of an application.

So, you cannot rely on playwright install to install the browsers. There is an alternative way to install the browsers. Indeed, playwright install is just a small utility that calls Microsoft.Playwright.Program.Run. This method is in Microsoft.Playwright.dll which is part of the Microsoft.Playwright NuGet package. This means you don't need the CLI to install the browsers. Instead, you can call the method directly from the code.

C#
using Microsoft.Playwright;

Console.WriteLine("Installing browsers");

// The following line installs the default browsers. If you only need a subset of browsers,
// you can specify the list of browsers you want to install among: chromium, chrome,
// chrome-beta, msedge, msedge-beta, msedge-dev, firefox, and webkit.
// var exitCode = Microsoft.Playwright.Program.Main(new[] { "install", "webkit", "chrome" });
// If you need to install dependencies, you can add "--with-deps"
var exitCode = Microsoft.Playwright.Program.Main(new[] { "install" });
if (exitCode != 0)
{
    Console.WriteLine("Failed to install browsers");
    Environment.Exit(exitCode);
}

Console.WriteLine("Browsers installed");

// Using playwright to launch a browser
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
await using var browserContext = await browser.NewContextAsync();
var page = await browserContext.NewPageAsync();
await page.GotoAsync("https://www.meziantou.net");
Console.WriteLine(await page.InnerTextAsync("h1"));

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub