WebView2
简介
以下将解释如何将 Playwright 与 Microsoft Edge WebView2 结合使用。WebView2 是一个 WinForms 控件,它将在底层使用 Microsoft Edge 来渲染 Web 内容。它是 Microsoft Edge 浏览器的一部分,可在 Windows 10 和 Windows 11 上使用。Playwright 可用于自动化 WebView2 应用程序,并可用于测试 WebView2 中的 Web 内容。为了连接到 WebView2,Playwright 使用 BrowserType.connectOverCDP(),它通过 Chrome DevTools 协议 (CDP) 连接到 WebView2。
概述
可以指示 WebView2 控件监听传入的 CDP 连接,方法是设置 WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
环境变量为 --remote-debugging-port=9222
,或者使用 --remote-debugging-port=9222
参数调用 EnsureCoreWebView2Async。这将启动启用 Chrome DevTools 协议的 WebView2 进程,从而允许 Playwright 进行自动化。9222 在这里只是一个示例端口,也可以使用任何其他未使用的端口。
await this.webView.EnsureCoreWebView2Async(await CoreWebView2Environment.CreateAsync(null, null, new CoreWebView2EnvironmentOptions()
{
AdditionalBrowserArguments = "--remote-debugging-port=9222",
})).ConfigureAwait(false);
一旦您的带有 WebView2 控件的应用程序正在运行,您就可以通过 Playwright 连接到它
Browser browser = playwright.chromium().connectOverCDP("https://127.0.0.1:9222");
BrowserContext context = browser.contexts().get(0);
Page page = context.pages().get(0);
为了确保 WebView2 控件已准备就绪,您可以等待 CoreWebView2InitializationCompleted
事件
this.webView.CoreWebView2InitializationCompleted += (_, e) =>
{
if (e.IsSuccess)
{
Console.WriteLine("WebView2 initialized");
}
};
编写和运行测试
默认情况下,WebView2 控件将对所有实例使用相同的用户数据目录。这意味着,如果您并行运行多个测试,它们将相互干扰。为了避免这种情况,您应该为每个测试将 WEBVIEW2_USER_DATA_FOLDER
环境变量(或使用 WebView2.EnsureCoreWebView2Async 方法)设置为不同的文件夹。这将确保每个测试都在其自己的用户数据目录中运行。
使用以下方法,Playwright 将把您的 WebView2 应用程序作为子进程运行,为其分配唯一的用户数据目录,并为您的测试提供 Page 实例
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);
}
}
}
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.net.cn");
Locator gettingStarted = page.getByText("Get started");
assertThat(gettingStarted).isVisible();
}
}
调试
在您的 webview2 控件中,您只需右键单击即可打开上下文菜单,然后选择“检查”以打开 DevTools,或按 F12 键。您还可以使用 WebView2.CoreWebView2.OpenDevToolsWindow 方法以编程方式打开 DevTools。
有关调试测试的信息,请参阅 Playwright 调试指南。