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 Protocol (CDP) 連接到它。
概觀
可以指示 WebView2 控制項透過設定具有 --remote-debugging-port=9222
的 WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
環境變數,或使用 --remote-debugging-port=9222
引數呼叫 EnsureCoreWebView2Async,來監聽傳入的 CDP 連線。這將啟動啟用 Chrome DevTools Protocol 的 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.dev.org.tw");
Locator gettingStarted = page.getByText("Get started");
assertThat(gettingStarted).isVisible();
}
}
偵錯
在您的 webview2 控制項內,您可以直接按一下滑鼠右鍵以開啟上下文選單,然後選取「檢查」以開啟 DevTools,或按下 F12。您也可以使用 WebView2.CoreWebView2.OpenDevToolsWindow 方法以程式設計方式開啟 DevTools。
如需偵錯測試,請參閱 Playwright 偵錯指南。