跳至主要内容

WebView2

简介

以下将解释如何使用Playwright与Microsoft Edge WebView2。WebView2是一个WinForms控件,它底层使用Microsoft Edge来渲染网页内容。它是Microsoft Edge浏览器的一部分,可在Windows 10和Windows 11上使用。Playwright可用于自动化WebView2应用程序,并可用于测试WebView2中的网页内容。为了连接到WebView2,Playwright使用BrowserType.connectOverCDP(),通过Chrome DevTools协议(CDP)与其建立连接。

概述

可以通过设置环境变量WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS--remote-debugging-port=9222,或者调用EnsureCoreWebView2Async方法并传入--remote-debugging-port=9222参数,来指示WebView2控件监听传入的CDP连接。这将启用Chrome开发者工具协议的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("http://localhost: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 Method)指向不同文件夹。这样可以确保每个测试都在自己的用户数据目录中运行。

使用以下方法,Playwright将以子进程方式运行您的WebView2应用程序,为其分配唯一的用户数据目录,并将Page实例提供给您的测试:

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

调试

在您的webview2控件内,只需右键点击即可打开上下文菜单并选择"Inspect"以打开开发者工具,或按下F12键。您也可以使用WebView2.CoreWebView2.OpenDevToolsWindow方法以编程方式打开开发者工具。

如需调试测试,请参阅Playwright的调试指南