Skip to main content

WebView2

Introduction

The following will explain how to use Playwright with Microsoft Edge WebView2. WebView2 is a WinForms control, which will use Microsoft Edge under the hood to render web content. It is a part of the Microsoft Edge browser and is available on Windows 10 and Windows 11. Playwright can be used to automate WebView2 applications and can be used to test web content in WebView2. For connecting to WebView2, Playwright uses BrowserType.connectOverCDP() which connects to it via the Chrome DevTools Protocol (CDP).

Overview

A WebView2 control can be instructed to listen to incoming CDP connections by setting either the WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS environment variable with --remote-debugging-port=9222 or calling EnsureCoreWebView2Async with the --remote-debugging-port=9222 argument. This will start the WebView2 process with the Chrome DevTools Protocol enabled which allows the automation by Playwright. 9222 is an example port in this case, but any other unused port can be used as well.

await this.webView.EnsureCoreWebView2Async(await CoreWebView2Environment.CreateAsync(null, null, new CoreWebView2EnvironmentOptions()
{
AdditionalBrowserArguments = "--remote-debugging-port=9222",
})).ConfigureAwait(false);

Once your application with the WebView2 control is running, you can connect to it via Playwright:

Browser browser = playwright.chromium().connectOverCDP("http://localhost:9222");
BrowserContext context = browser.contexts().get(0);
Page page = context.pages().get(0);

To ensure that the WebView2 control is ready, you can wait for the CoreWebView2InitializationCompleted event:

this.webView.CoreWebView2InitializationCompleted += (_, e) =>
{
if (e.IsSuccess)
{
Console.WriteLine("WebView2 initialized");
}
};

Writing and running tests

By default, the WebView2 control will use the same user data directory for all instances. This means that if you run multiple tests in parallel, they will interfere with each other. To avoid this, you should set the WEBVIEW2_USER_DATA_FOLDER environment variable (or use WebView2.EnsureCoreWebView2Async Method) to a different folder for each test. This will make sure that each test runs in its own user data directory.

Using the following, Playwright will run your WebView2 application as a sub-process, assign a unique user data directory to it and provide the Page instance to your test:

WebView2Process.java
package com.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class WebView2Process {
public int cdpPort;
private Path _dataDir;
private Process _process;
private Path _executablePath = Path.of("../webview2-app/bin/Debug/net8.0-windows/webview2.exe");

public WebView2Process() throws IOException {
cdpPort = nextFreePort();
_dataDir = Files.createTempDirectory("pw-java-webview2-tests-");

if (!Files.exists(_executablePath)) {
throw new RuntimeException("Executable not found: " + _executablePath);
}
ProcessBuilder pb = new ProcessBuilder().command(_executablePath.toAbsolutePath().toString());
Map<String, String> envMap = pb.environment();
envMap.put("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--remote-debugging-port=" + cdpPort);
envMap.put("WEBVIEW2_USER_DATA_FOLDER", _dataDir.toString());
_process = pb.start();
// wait until "WebView2 initialized" got printed
BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()));
while (true) {
String line = reader.readLine();
if (line == null) {
throw new RuntimeException("WebView2 process exited");
}
if (line.contains("WebView2 initialized")) {
break;
}
}
}

private static final AtomicInteger nextUnusedPort = new AtomicInteger(9000);

private static boolean available(int port) {
try (ServerSocket ignored = new ServerSocket(port)) {
return true;
} catch (IOException ignored) {
return false;
}
}

static int nextFreePort() {
for (int i = 0; i < 100; i++) {
int port = nextUnusedPort.getAndIncrement();
if (available(port)) {
return port;
}
}
throw new RuntimeException("Cannot find free port: " + nextUnusedPort.get());
}

public void dispose() {
_process.destroy();
try {
_process.waitFor();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
TestExample.java
package com.example;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import org.junit.jupiter.api.*;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

import java.io.IOException;

public class TestExample {
// Shared between all tests in this class.
static WebView2Process webview2Process;
static Playwright playwright;
static Browser browser;
static BrowserContext context;
static Page page;

@BeforeAll
static void launchBrowser() throws IOException {
playwright = Playwright.create();
webview2Process = new WebView2Process();
browser = playwright.chromium().connectOverCDP("http://127.0.0.1:" + webview2Process.cdpPort);
context = browser.contexts().get(0);
page = context.pages().get(0);
}

@AfterAll
static void closeBrowser() {
webview2Process.dispose();
}

@Test
public void shouldClickButton() {
page.navigate("https://playwright.dev");
Locator gettingStarted = page.getByText("Get started");
assertThat(gettingStarted).isVisible();
}
}

Debugging

Inside your webview2 control, you can just right-click to open the context menu and select "Inspect" to open the DevTools or press F12. You can also use the WebView2.CoreWebView2.OpenDevToolsWindow method to open the DevTools programmatically.

For debugging tests, see the Playwright Debugging guide.