跳到主要內容

Chrome 擴充功能

簡介

注意

擴充功能僅適用於使用持久性上下文啟動的 Chrome / Chromium。使用自訂瀏覽器參數的風險由您自行承擔,因為其中一些參數可能會破壞 Playwright 功能。

以下程式碼片段檢索位於 ./my-extension背景頁面Manifest v2 擴充功能。

請注意使用 chromium 通道,以便在無頭模式下執行擴充功能。或者,您可以以有頭模式啟動瀏覽器。

const { chromium } = require('playwright');

(async () => {
const pathToExtension = require('path').join(__dirname, 'my-extension');
const userDataDir = '/tmp/test-user-data-dir';
const browserContext = await chromium.launchPersistentContext(userDataDir, {
channel: 'chromium',
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
let [backgroundPage] = browserContext.backgroundPages();
if (!backgroundPage)
backgroundPage = await browserContext.waitForEvent('backgroundpage');

// Test the background page as you would any other page.
await browserContext.close();
})();

測試

為了在執行測試時載入擴充功能,您可以使用測試夾具來設定上下文。您也可以動態檢索擴充功能 ID,並使用它來載入和測試彈出頁面,例如。

請注意使用 chromium 通道,以便在無頭模式下執行擴充功能。或者,您可以以有頭模式啟動瀏覽器。

首先,新增將載入擴充功能的夾具

fixtures.ts
import { test as base, chromium, type BrowserContext } from '@playwright/test';
import path from 'path';

export const test = base.extend<{
context: BrowserContext;
extensionId: string;
}>({
context: async ({ }, use) => {
const pathToExtension = path.join(__dirname, 'my-extension');
const context = await chromium.launchPersistentContext('', {
channel: 'chromium',
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
],
});
await use(context);
await context.close();
},
extensionId: async ({ context }, use) => {
/*
// for manifest v2:
let [background] = context.backgroundPages()
if (!background)
background = await context.waitForEvent('backgroundpage')
*/

// for manifest v3:
let [background] = context.serviceWorkers();
if (!background)
background = await context.waitForEvent('serviceworker');

const extensionId = background.url().split('/')[2];
await use(extensionId);
},
});
export const expect = test.expect;

然後在測試中使用這些夾具

import { test, expect } from './fixtures';

test('example test', async ({ page }) => {
await page.goto('https://example.com');
await expect(page.locator('body')).toHaveText('Changed by my-extension');
});

test('popup page', async ({ page, extensionId }) => {
await page.goto(`chrome-extension://${extensionId}/popup.html`);
await expect(page.locator('body')).toHaveText('my-extension popup');
});