Học Playwright tiếng Việt, Cộng đồng Playwright cho người Việt

Vọc Vạch Playwright

[Vọc Playwright] – Webview2

https://playwright.dev/docs/webview2

Introduction

  • WebView2 là 1 công cụ mạnh mẽ cho phép bạn hiển thị nội dung web trong ứng dụng WinForms bằng Microsoft Edge
  • Playwright có thể automate các ứng dụng WebView2 và kiểm tra nội dung web trong WebView2, kết nối với WebView2 thông qua browserType.connectOverCDP(), sử dụng Chrome DevTools Protocol (CDP)

Overview

  • Để cho phép WebView2 kết nối với Playwright, bạn cần bật chế độ debug bằng cách cài đặt biến môi trường WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS thành –remote-debugging-port=9222 hoặc gọi hàm EnsureCoreWebView2Async với tham số –remote-debugging-port=9222. Hành động này sẽ khởi động WebView2 với Chrome DevTools Protocol (CDP) được bật
await this.webView.EnsureCoreWebView2Async(await CoreWebView2Environment.CreateAsync(null, null, new CoreWebView2EnvironmentOptions()
{
  AdditionalBrowserArguments = "--remote-debugging-port=9222",
})).ConfigureAwait(false);
  • Sau khi ứng dụng WebView2 của bạn chạy, bạn có thể kết nối nó bằng Playwright
const browser = await playwright.chromium.connectOverCDP('http://localhost:9222');
const context = browser.contexts()[0];
const page = context.pages()[0];
  • Để đảm bảo WebView2 sẵn sàng, bạn có thể chờ CoreWebView2InitializationCompleted event
this.webView.CoreWebView2InitializationCompleted += (_, e) =>
{
    if (e.IsSuccess)
    {
        Console.WriteLine("WebView2 initialized");
    }
};

Writing and running tests

  • Mặc định, WebView2 sử dụng cùng 1 thư mục dữ liệu người dùng cho tất cả các phiên bản. Điều này có nghĩa là nếu bạn chạy nhiều test song song, chúng sẽ cản trở lẫn nhau. Để tránh điều này, bạn nên đặt biến môi trường WEBVIEW2_USER_DATA_FOLDER (hoặc sử dụng phương thức WebView2.EnsureCoreWebView2Async) thành 1 thư mục khác cho mỗi test. Hành động này sẽ đảm bảo mỗi test chạy trong thư mục dữ liệu người dùng riêng biệt của nó
  • Dưới đây là cách Playwright chạy ứng dụng WebView2 của bạn như 1 sub-process. Gán 1 thư mục dữ liệu người dùng duy nhất cho nó và cung cấp Page instance cho test:
// webView2Test.ts
import { test as base } from '@playwright/test';
import fs from 'fs';
import os from 'os';
import path from 'path';
import childProcess from 'child_process';

const EXECUTABLE_PATH = path.join(
    __dirname,
    '../../webview2-app/bin/Debug/net8.0-windows/webview2.exe',
);

export const test = base.extend({
  browser: async ({ playwright }, use, testInfo) => {
    const cdpPort = 10000 + testInfo.workerIndex;
    // Make sure that the executable exists and is executable
    fs.accessSync(EXECUTABLE_PATH, fs.constants.X_OK);
    const userDataDir = path.join(
        fs.realpathSync.native(os.tmpdir()),
        `playwright-webview2-tests/user-data-dir-${testInfo.workerIndex}`,
    );
    const webView2Process = childProcess.spawn(EXECUTABLE_PATH, [], {
      shell: true,
      env: {
        ...process.env,
        WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${cdpPort}`,
        WEBVIEW2_USER_DATA_FOLDER: userDataDir,
      }
    });
    await new Promise<void>(resolve => webView2Process.stdout.on('data', data => {
      if (data.toString().includes('WebView2 initialized'))
        resolve();
    }));
    const browser = await playwright.chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`);
    await use(browser);
    await browser.close();
    childProcess.execSync(`taskkill /pid ${webView2Process.pid} /T /F`);
    fs.rmdirSync(userDataDir, { recursive: true });
  },
  context: async ({ browser }, use) => {
    const context = browser.contexts()[0];
    await use(context);
  },
  page: async ({ context }, use) => {
    const page = context.pages()[0];
    await use(page);
  },
});

export { expect } from '@playwright/test';
// example.spec.ts
import { test, expect } from './webView2Test';

test('test WebView2', async ({ page }) => {
  await page.goto('https://playwright.dev');
  const getStarted = page.getByText('Get Started');
  await expect(getStarted).toBeVisible();
});

Debugging

  • Trong WebView2, bạn có thể click chuột phải để mở context menu và chọn “Inspect” để mở devtools hoặc nhấm F12. Bạn có thể sử dụng phương thức WebView2.CoreWebView2.OpenDevToolsWindow để mở devtools theo cách lập trình
  • Để debugging tests, xem tại: https://playwright.dev/docs/debug

Trả lời